access HttpContext.Current from WCF Web Service

痴心易碎 提交于 2019-11-27 18:22:14

You can get access to HttpContext.Current by enabling AspNetCompatibility, preferably via configuration:

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

That in turn allows you to get access to the current user: HttpContext.Current.User - which is what you're after, right?

You can even enforce AspNetCompatibility by decorating your service class with an additional attribute:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

(In the System.ServiceModel.Activation namespace.) If that attribute is in place, your service will fail to start unless AspNetCompatibility is enabled!

You do not have a HttpContext by default but you have many of the same objects present in the OperationContext (which is always present) or the WebOperationContext (which is only available for certain bindings.

You can access the OperationContext or WebOperationContext by using the static .Current property like so: WebOperationContext.Current

In case you don't want to change Web.config or you cannot change it:

private string GetClientIPAddress()
        {
            var props = OperationContext.Current.IncomingMessageProperties;
            var endpointProperty = props[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            if (endpointProperty != null)
            {
                if (endpointProperty.Address == "::1" || String.IsNullOrEmpty(endpointProperty.Address))
                    return "127.0.0.1";

                return endpointProperty.Address;
            }

            return String.Empty;
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!