Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rest

c#

.net

http

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

like image 421
beaumondo Avatar asked Aug 06 '13 10:08

beaumondo


People also ask

How do I find HTTP header information?

In Chrome, visit a URL(such as https://www.google.com ), right click, select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.

How do I find a header URL?

Open the webpage whose headers have to be checked. Right click and select 'Inspect' to open developer tools. Select the network tab and refresh or reload the page. Select any HTTP request from the left panel and the header will be displayed on the right.

What information can you gather from HTTP headers?

HTTP response header Response headers are sent by a web server in HTTP transaction responses. Response headers often contain information on whether the initial request went through, type of connection, encoding etc. If the request did not go through, then HTTP response headers will contain an error code.


2 Answers

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" + "}";
    }
like image 160
beaumondo Avatar answered Nov 15 '22 08:11

beaumondo


Have you tried

Request.Headers["Authorization"]

like image 45
Haris Hasan Avatar answered Nov 15 '22 08:11

Haris Hasan