2

How can I get the header properties from a jquery ajax call. I am sending a code in the header so I need to read it in the webmethods:

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

2 Answers2

9

On the client-side (I am assuming asmx as you requested the webmethod), you can use the HttpContext.Current to get the current HttpContext. By reading the Request, you can get the headers.

An example to read all the headers would be:

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;
}

To read your specific header, you can read the

HttpContext.Current.Request.Headers['aaa']
Jazerix
  • 4,729
  • 10
  • 39
  • 71
Icepickle
  • 12,689
  • 3
  • 34
  • 48
0

$ajax is just a wrapper around XMLHttpRequest so you can use 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!'); }
     });
});

My testing yields:

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
Crowcoder
  • 11,250
  • 3
  • 36
  • 45