Trying to get the user-agent from request in asp.net web api self host

后端 未结 5 1842
轻奢々
轻奢々 2021-02-05 00:21

I\'m trying to get the user-agent in a web api self host and I\'m either doing it wrong, or the web api itself is altering the user agent string.

I\'ve tried using sever

相关标签:
5条回答
  • 2021-02-05 00:39

    The absolutely simplest way to get the full user-agent from inside a WebAPI-controller is by doing this:

    var userAgent = Request.Headers.UserAgent.ToString();
    

    It gives exactly the same result as doing the manual step like this:

    // var headers = request.Headers.GetValues("User-Agent");
    // var userAgent = string.Join(" ", headers);
    
    0 讨论(0)
  • 2021-02-05 00:44

    The answer is simple try the following. It's shorter and less likely to break.

    String userAgent;
    userAgent = Request.UserAgent;
    

    It will give you a string similar to this one.

    Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)
    

    Documentation: http://msdn.microsoft.com/en-us/library/system.web.httprequest.useragent.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

    0 讨论(0)
  • 2021-02-05 00:45
    var context = new HttpContextWrapper(HttpContext.Current);
    HttpRequestBase request = context.Request;
    var browserdetail = request.UserAgent;
    

    This worked for me if you want only browser name then simply write:

    var browserdetail = request.browser
    

    And if you want clients ip address then simply do:

    var browserdetail = request.hostaddress and use it for generating token key for authenticaton.

    0 讨论(0)
  • 2021-02-05 00:52

    .NET Core 2.0(+)

    As Simple as Request.Headers["User-Agent"] (returns as string) ;)

    0 讨论(0)
  • 2021-02-05 00:55

    Oops, figured it out, answering it myself in case anyone else runs into this. Apparently the user-agent gets chopped up.

    This gives me the full user-agent:

    // Default empty user agent.
    String userAgent = "";
    
    // Get user agent.
    if (Request.Headers.Contains("User-Agent"))
    {
        var headers = request.Headers.GetValues("User-Agent");
    
        StringBuilder sb = new StringBuilder();
    
        foreach (var header in headers)
        {
            sb.Append(header);
    
            // Re-add spaces stripped when user agent string was split up.
            sb.Append(" ");
        }
    
        userAgent = sb.ToString().Trim();
    }
    
    0 讨论(0)
提交回复
热议问题