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;
}
}
}