6

我有以下 C# RESTful 交互。

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

在以下类中实现

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

我想将 http 标头中“授权”字段的值传递给此方法(如注释行中所述)。任何想法我可以如何检索这个值

4

3 回答 3

8

我能够使用 HttpContext.Current 属性获得我想要的东西。使用 Request.Headers 属性,我能够检索标题信息的名称值列表

    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" + "}";
    }
于 2013-08-06T12:18:59.973 回答
2

你有没有尝试过

Request.Headers["Authorization"]

于 2013-08-06T10:19:41.060 回答
-1

将@beaumondo 快速翻译成VB .Net,由于某种原因,我在过去几个月里一直在使用它。

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

非常感谢,我不知道为什么我以前找不到关于 HttpContext.Current.Request.Headers 更容易。

于 2016-06-28T14:03:38.830 回答