简体   繁体   中英

HttpContext.Current.User is null after installing .NET Framework 4.5

I was using .NET 4.0 VS10. I had working WCF services that were using forms authentication. I upgraded to VS11, .NET 4.5.

Now my HttpContext.Current.User is null, in a wcf request. I injected a cookie from login to this request.

HttpRequestMessageProperty httpRequest;
...
httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookie);

Any ideas how to make it work again?

Already have the

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

and the

[AspNetCompatibilityRequirements(RequirementsMode = spNetCompatibilityRequirementsMode.Required)]

If you are running into this issue in an Oneway (operations marked with [OperationContract(IsOneWay=true)] ) WCF operation contract, here is the reason for the issue. HttpContext is an asp.net construct. After a one way operation is successfully invoked the service model sends back a 202 (Accepted) reply back to the client.

  • In 4.5 asp.net clears away the HttpContext as the response has been sent back to the client already which is by design.
  • In 4.0 this is just a happy coincidence that this unsupported scenario worked.

Since we found a few customer reports on this, a quirked fix is made in .net 4.5.1 update. To give more details about the fix:

  1. If your project is still targeting 4.0 & you are running your application on a 4.5.1 machine then your issue will be fixed (Internally checks for the target framework version).
  2. If your project is retargeted to 4.5 then Httpcontext.Current.User will again become null for the reasons I mentioned above. Try using OperationContext.Current.ServiceSecurityContext.WindowsIdentity to get the user identity instead of HttpContext.Current.User property. This property is host independent and gets populated when your client is authenticated.

There's a solution to a similar problem here :

Add

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

to your config file.

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