How to detect user agent in WCF web service

落爺英雄遲暮 提交于 2019-11-30 05:03:07

问题


How can I detect the user agent in a web service? My web service is implemented using a WCF webservice with basicHTTPBinding. It will be a post from some SOAP clients. I wish to know the user-agent from the clients.

I shall like to see some sample code for this.

I am using a WCF based web service and in the svc.cs, I tried to catch this.Context.Request.UserAgent. But it gives the following error:

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?)

I also tried System.Web.HttpContext.Current.Request.UserAgent and it says:

'System.Web.HttpContext.Current' is null

Edit note:

I tried to activate the ASP.NET compatibility mode. I added <serviceHostingEnvironment aspNetCompatibilityEnabled="true" /> in the config file and added [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] on the top of the class that implements the service interface. Then using System.Web.HttpContext.Current.Request.UserAgent gives me the user agent as desired.


回答1:


You can read user agent from the HttpContext.Current.Request object if you enable ASP.NET compatibility in web.config:




回答2:


There is another way to get the user agent without enabling ASP.NET compatibility in web.config:

string userAgent = WebOperationContext.Current.IncomingRequest.Headers["User-Agent"];



回答3:


You can use also:

WebOperationContext.Current.IncomingRequest.UserAgent




回答4:


What a totally unhelpful response!

This is not a trivial task. Yes it is obviously possible to get te user-agent string but how does one actually do it? I spent 2 hours checking google and so on but found the answer buried in MSDN documentation. In Visual Studio, from within a WebMethod try

this.Context.Request.UserAgent

That should do it!




回答5:


User-Agent is a standard HTTP header. It'll be available to your web service just like it's available to anything CGI-like.

Did you even bother searching for this before posting your question? There must be millions of hits for it on Google.



来源:https://stackoverflow.com/questions/2759866/how-to-detect-user-agent-in-wcf-web-service

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