如何在WCF Web服务中检测用户代理

Kan*_*kan 6 wcf user-agent web-services

如何在Web服务中检测用户代理?我的Web服务是使用带有basicHTTPBinding的WCF Web服务实现的.它将是一些SOAP客户端的帖子.我希望了解客户的用户代理.

我想看一些示例代码.

我正在使用基于WCF的Web服务,在svc.cs中,我试图捕获this.Context.Request.UserAgent.但它给出了以下错误:

this.Context.Request.UserAgent 'MySoapService.MyService' does not contain a definition for 'Context' and no extension method 'Context' accepting a first argument of type 'MySoapService.MyService' could be found (are you missing a using directive or an assembly reference?)
Run Code Online (Sandbox Code Playgroud)

我也试过System.Web.HttpContext.Current.Request.UserAgent,它说:

'System.Web.HttpContext.Current' is null
Run Code Online (Sandbox Code Playgroud)

编辑说明:

我试图激活ASP.NET兼容模式.我<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />在配置文件中添加并添加[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] 到实现服务接口的类的顶部.然后使用System.Web.HttpContext.Current.Request.UserAgent根据需要为我提供用户代理.

Gab*_*iel 12

还有另一种方法来获取用户代理而不在web.config中启用ASP.NET兼容性:

string userAgent = WebOperationContext.Current.IncomingRequest.Headers["User-Agent"];
Run Code Online (Sandbox Code Playgroud)


小智 6

你也可以使用:

WebOperationContext.Current.IncomingRequest.UserAgent


Iha*_*ury 3

如果在 web.config 中启用 ASP.NET 兼容性,则可以从 HttpContext.Current.Request 对象读取用户代理: