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"
}
});
On the client side (i am asuming 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 == 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;
}
To read your specific header, you can read the
HttpContext.Current.Request.Headers['aaa']
$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\r\nPragma: no-cache\r\nContent-Type: application/json; charset=utf-8\r\nExpires: -1\r\nServer: Microsoft-IIS/8.0\r\nX-AspNet-Version: 4.0.30319\r\nX-SourceFiles: =?UTF-8?B?YzpcdcnNcYm9iX3VtZW50cdsf3x1x2aXNgc3R1ZGlvIDIwMTNcUHJvHNcVml0xwfgbYWxBUElcVml0YWxBUElcYXBpXENvb3JkaW5hdG9y?=\r\nX-Powered-By: ASP.NET\r\nDate: Wed, 21 Jan 2015 00:37:03 GMT\r\nContent-Length: 21034\r\n\r\n