简体   繁体   中英

How to retrieve HTTP header information from a C# RESTful Service Method

I have the following C# RESTful interace.

    [WebGet(UriTemplate = "requires-authorization", ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string MethodRequiringAuthorization();

Which is implemented int the following class

    public string MethodRequiringAuthorization()
    {
        //var authorisazation = HTTP header authorization field
        return "{Message" + ":" + "You-accessed-this-message-with-authorization" + "}";
    }

I would like to pass into this method the value of the field "Authorization" in the http header (as described in the commented line). Any ideas how I can retrieve this value

I was able to get what I was looking for using the HttpContext.Current property. Using the Request.Headers property I was able to retrieve a name value list of the header information

    public string MethodRequiringAuthorization()
    {
        HttpContext httpContext = HttpContext.Current;
        NameValueCollection headerList = httpContext.Request.Headers;
        var authorizationField = headerList.Get("Authorization");            
        return "{Message" + ":" + "You-accessed-this-message-with-authorization" + "}";
    }

你有没有尝试过

Request.Headers["Authorization"]

Quick translation of @beaumondo into VB .Net, which for some reason I've been using again for the last few months.

Private Function GetAuthorizationFromHeader() As String
    Dim currentContext As HttpContext = HttpContext.Current
    Dim headerList As NameValueCollection = currentContext.Request.Headers
    Dim authorizationField As String = headerList.Get("Authorization")
    Return authorizationField '"{Message" + ":" + "You-accessed-this-message-with-authorization" + "}"message-with-authorization" + "}"
End Function

Thank you so much, I don't know why I couldn't find about HttpContext.Current.Request.Headers easier before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM