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

后端 未结 5 1844
轻奢々
轻奢々 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: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();
    }
    

提交回复
热议问题