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

15,305

Solution 1

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" + "}";
    }

Solution 2

Have you tried

Request.Headers["Authorization"]

Share:
15,305
beaumondo
Author by

beaumondo

Updated on June 12, 2022

Comments

  • beaumondo
    beaumondo almost 2 years

    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