简体   繁体   中英

Testing ASMX webservice using NUnit and transferring session state

I have a NUnit test class that starts an ASP.NET web service (using Microsoft.VisualStudio.WebHost.Server) which runs on http://localhost:1070

The problem I am having is that I want to create a session state within the NUnit test that is accessible by the ASP.NET web service on localhost:1070.
I have done the following, and the session state can be created successfully inside the NUnit Test, but is lost when the web service is invoked:

//Create a new HttpContext for NUnit Testing based on:
//http://blogs.imeta.co.uk/jallderidge/archive/2008/10/19/456.aspx
HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://localhost:1070/", ""), new HttpResponse(
     new System.IO.StringWriter()));

//Create a new HttpContext.Current for NUnit Testing
System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(
 HttpContext.Current, new HttpSessionStateContainer("",
  new SessionStateItemCollection(),
  new HttpStaticObjectsCollection(), 20000, true,
  HttpCookieMode.UseCookies, SessionStateMode.Off, false));

HttpContext.Current.Session["UserName"] = "testUserName";
testwebService.testMethod(); 

I want to be able to get the session state created in the NUnit test for Session["UserName"] in the ASP.NET web service:

[WebMethod(EnableSession=true)]
public int testMethod()
{
    string user; 

    if(Session["UserName"] != null)
    {
       user = (string)Session["UserName"];

      //Do some processing of the user
      //user is validated against with value stored in database
      return 1;
    }
    else
      return 0;
}

The web.config file has the following configuration for the session state configuration and would like to remain using InProc than rather StateServer Or SQLServer:

<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" cookieless="false" timeout="20"/> 

可以使用HttpContextBase 。来代替实际的HttpContext类,然后模拟会话,响应,请求等。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM