从WCF Web服务访问HttpContext.Current
我刚开始在ASP.NET AJAX中使用WCF服务。我从Javascript实例化我的WCF服务,然后将字符串变量作为参数传递给我的WCF服务方法(带有OperationContract签名)。然后,我返回一个.NET对象(用DataContract定义),它绑定到我的自定义Javascript类。基于登录到我的Web会话的用户,我遇到了身份验证问题。但是,WCF Web服务是一种完全不同的服务,对于HttpContext.Current对象没有上下文。什么是最安全的方式来访问该对象?从WCF Web服务访问HttpContext.Current
您可以通过启用AspNetCompatibility可以访问HttpContext.Current
,最好通过配置:
<configuration>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
</configuration>
这反过来又允许你访问当前用户:HttpContext.Current.User
- 这就是你要的,对吧?
你甚至可以通过附加属性装饰你的服务类强制AspNetCompatibility:(在System.ServiceModel.Activation
命名空间)
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
如果该属性是到位,您的服务将无法启动,除非AspNetCompatibility是启用!
您没有HttpContext的默认,但你有很多的的OperationContext存在于同一对象(总是存在)或WebOperationContext(这是仅适用于特定的绑定。
您可以访问的OperationContext或WebOperationContext通过静态.Current
属性,像这样:WebOperationContext.Current
+1这应该是公认的答案。我们正在处理可以托管在Windows服务或自托管的WCF。 AspNetCompatilibity只是一个老习惯。 – Askolein 2014-03-11 10:18:57
如果你不想改变的Web.config或你不能改变它:
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;
}
感谢您的意见。我给了你一点。一旦我测试完了,我会标记我的答案。我们在应用程序中存储用户的方式稍有不同,因此我们必须重新设计他们推荐的表单身份验证。然后我可以使用这种方法。 – MacGyver 2011-05-19 22:05:02
值得注意的是,这只有在您的服务托管在IIS中时才有效。 – 2015-11-09 11:56:29