7

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

4
  • maybe using this.Request ? Commented Aug 6, 2013 at 10:18
  • 1
    ps: you may find this useful forums.asp.net/p/1193533/2056217.aspx Commented Aug 6, 2013 at 10:22
  • Considering the attributes he uses above his method declaration it is safe to assume he uses WCF Rest instead of ASP.NET Web API. This means the Request property is not present. Commented Aug 6, 2013 at 11:29
  • Yeah it didnt really help but cheers for looking Commented Aug 6, 2013 at 12:19

3 Answers 3

8

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" + "}"; } 
Sign up to request clarification or add additional context in comments.

Comments

2

Have you tried

Request.Headers["Authorization"]

1 Comment

I tried that from lookng at another post, but i dont have that option (Request.Headers) in scope.
-1

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.

1 Comment

While this may be accurate, the question doesn't ask for vb.net. it asks for c#. No one looking for vb.net will find this, since the lack of the tag will exclude this question from the search results.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.