0

I have a web-service written in C# that I am consuming. I now need to make use of session state in order so that I can maintain state in between web-service calls. I've read online that I need to use internal state collections for that. I declared a class MyDemo that has session state turned on on its method HelloWorld(). However, an exception System.InvalidOperationException (HttpContext is not available. This class can only be used in the context of an ASP.NET request.) is thrown when I try to call method HelloWorld(). Am I using internal state collections correctly? How should I fix my program?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web.Services;

namespace GettingStartedLib
{

    public class MyDemo : System.Web.Services.WebService
    {
        [WebMethod(EnableSession = true)]
        public string HelloWorld()
        {
            // get the Count out of Session State
            int Count;

            if (Session["Count"] == null)
                Count = 0;
            else
                Count = (int)Session["Count"];

            if (Count == null)
                Count = 0;

            // increment and store the count
            Count++;
            Session["Count"] = Count;

            return "Hello World - Call Number: " + Count.ToString();
        }
    }

    public class CalculatorService : ICalculator
    {
        private int x = 0;

        [WebMethod(EnableSession = true)] 
        public double Add(double n1, double n2)
        {

            MyDemo demo = new MyDemo();
            string sample = demo.HelloWorld();


            x++;
            Console.WriteLine("x = {0}", x);

            double result = n1 + n2;
            Console.WriteLine("Received Add({0},{1})", n1, n2);
            // Code added to write output to the console window.
            Console.WriteLine("Return: {0}", result);
            return result;
        }
    }
}
user3623874
  • 520
  • 1
  • 6
  • 25
  • I believe it's because the context cannot be passed to the HelloWorld. Additionally, does ICalculator inherit from System.Web.Services.WebService? If it doesn't that may also be part of the problem. – Mark Fitzpatrick Oct 21 '14 at 03:36
  • No, it does not, but I am able to make web-service calls on CalculatorService. Here is the code for ICalculator interface: [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] public interface ICalculator { [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); } And what should I do about passing the context to HelloWorld? – user3623874 Oct 21 '14 at 04:31

0 Answers0