简体   繁体   中英

HTTPContext for webservices

HttpContext.Current.Request.ServerVariables["SERVER_PORT"] HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"] HttpContext.Current.Request.ServerVariables["SERVER_NAME"] HttpContext.Current.Request.ApplicationPath

I want to access these value via a webservice -C#, whenever I call these values in webservice I get null for all of the above, where as above works for web pages (aspx).

As others have mentioned, you need to enable ASP.NET compatibility. You can also enable this via configuration if you don't want to limit your code via attributes like so:

<system.serviceModel>        
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

Here's a great resource that helped explain to me the underlying functionality and trade-offs made by enabling compatibility mode.

What sort of web service are you using? asmx or wcf? They should work fine with asmx services but if you're using WCF, you'll need to add the following attribute to the method:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

If it is a WCF web service you can do the following:

[AspNetCompatibilityRequirementsAttribute(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class FooBar : IFooBar
{
   public void DoSomething()
   {
       HttpContext context = HttpContext.Current;
       if (context != null)
       {
             // Should get here now
       }
   }

}

The key is to add [AspNetCompatibilityRequirementsAttribute(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] .

have you tried to define your method with EnableSession at true?

[WebMethod(EnableSession = true)]
    public string your_public_method(your_params)
    { [...] }

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