如何从C#RESTful服务方法中检索HTTP标头信息
本文关键字:HTTP 检索 信息 方法 C#RESTful 服务 | 更新日期: 2023-09-27 18:26:38
我有以下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头中字段"Authorization"的值传递给这个方法(如注释行中所述)。有什么想法我可以检索这个值
我能够使用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" + "}";
}
你试过吗
Request.Headers["Authorization"]
将@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。