从网络方法获取 header

Get header from web method

如何从 jquery ajax 调用中获取 header 属性。我正在 header 中发送代码,所以我需要在 webmethods 中阅读它:

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

$ajax 只是 XMLHttpRequest 的包装器,因此您可以使用 getAllResponseHeaders()

$(document).ready(function () {
    var hdrs = $.ajax({
        type: "GET",
        url: "http://localhost:54220/api/FooApi",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            console.log(JSON.stringify(jqXHR.getAllResponseHeaders()));
        },
        error: function () { alert('boo!'); }
     });
});

我的测试产量:

Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json;charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?YzpcdcnNcYm9iX3VtZW50cdsf3x1x2aXNgc3R1ZGlvIDIwMTNcUHJvHNcVml0xwfgbYWxBUElcVml0YWxBUElcYXBpXENvb3JkaW5hdG9y?=
X-Powered-By: ASP.NET
Date: Wed, 21 Jan 2015 00:37:03 GMT
Content-Length: 21034

在 client-side 上(我假设您请求 web 方法时使用 asmx),您可以使用 HttpContext.Current 获取当前的 HttpContext。通过读取Request,可以得到headers.

读取所有 header 的示例是:

public string GetRequestHeaders()
{
    HttpContext ctx = HttpContext.Current;
    if (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;
}

要阅读您的特定header,您可以阅读

HttpContext.Current.Request.Headers['aaa']