从Web方法获取标头

Fle*_*ano 2 c# webmethod

如何从jquery ajax调用获取标头属性。我正在标题中发送代码,因此我需要在web方法中阅读它:

$.ajax({
    type: "POST",
    url: url,
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: success,
    error: error,
    headers: {
        'aaaa': "code"
    }
});
Run Code Online (Sandbox Code Playgroud)

Ice*_*kle 5

在客户端(我按照您要求的Web方法使用asmx),可以使用HttpContext.Current来获取当前的HttpContext。通过阅读请求,您可以获取标题。

读取所有标头的示例为:

public string GetRequestHeaders()
{
    HttpContext ctx = HttpContext.Current;
    if (ctx == null || ctx.Request == null || ctx.Request.Headers == null)
    {
        return string.Empty;
    }
    string headers = string.Empty;
    foreach (string header in ctx.Request.Headers.AllKeys)
    {
        string[] values = ctx.Request.Headers.GetValues(header);
        headers += string.Format("{0}: {1}", header, string.Join(",", values));
    }

    return headers;
}
Run Code Online (Sandbox Code Playgroud)

要阅读您的特定标题,您可以阅读

HttpContext.Current.Request.Headers['aaa']
Run Code Online (Sandbox Code Playgroud)