如何从C#RESTful服务方法中检索HTTP标头信息

时间:2013-08-06 10:13:35

标签: c# .net rest http

我有以下C#RESTful interace。

    [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头中“授权”字段的值(如注释行中所述)。我有什么想法可以检索这个值

3 个答案:

答案 0 :(得分: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" + "}";
    }

答案 1 :(得分:2)

你试过吗

Request.Headers["Authorization"]

答案 2 :(得分:-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的原因。