如何从.NET的Request Headers中提取嵌套对象的customId值?
问题描述
前端通过jQuery的$.ajax发送请求时,使用getcustomHeaders()返回的嵌套对象作为请求头:
getcustomHeaders()返回的对象结构:
{ "customHeaders": { "customId": "26", "screenData": "width=1920&height=1080&scaling-factor=1&colour-depth=24", "screenSize": "width=1920&height=1080" } }
AJAX请求代码:
$.ajax({ url: 'someName/Submit?productId=' + productId, type: 'post', headers: getcustomHeaders() }) .success(function(d) { if (d && d.responseJSON && d.responseJSON.Message) { alert(d.responseJSON.Message); } }) .error(function(d) { if (d && d.responseJSON && d.responseJSON.Message) { alert(d.responseJSON.Message); } else { alert(display_some_error_message); } });
后端通过HttpContext.Current.Request获取请求后,request.Headers["customHeaders"]能拿到值,但无法直接访问其中的customId,尝试以下两种方式均报错:
// 报错:NameValueCollection doesn't contain a definition for 'customHeaders' request.Headers["customHeaders"]["customId"] // 报错:'string' does not contain a definition for 'GetValues' request.Headers["customHeaders"].GetValues("customId").FirstOrDefault()
解决方案
问题根源:jQuery在处理嵌套对象作为请求头时,会将外层的customHeaders对应的嵌套对象序列化为JSON字符串放到请求头中,因此后端拿到的是一个JSON格式的字符串,而非可直接索引的集合。
有两种可行的解决方式:
方式一:调整前端请求头结构
修改getcustomHeaders(),直接返回内层的键值对,而非嵌套对象:
function getcustomHeaders() { return { "customId": "26", "screenData": "width=1920&height=1080&scaling-factor=1&colour-depth=24", "screenSize": "width=1920&height=1080" }; }
此时后端可直接通过request.Headers["customId"]获取对应值。
方式二:后端反序列化JSON字符串
如果前端无法修改,后端将拿到的JSON字符串反序列化为对象后再访问customId:
方法1:使用动态类型(需引用Newtonsoft.Json)
using Newtonsoft.Json; var customHeadersStr = request.Headers["customHeaders"]; var customHeaders = JsonConvert.DeserializeObject<dynamic>(customHeadersStr); var customId = customHeaders.customId;
方法2:定义实体类反序列化
先定义对应实体类:
public class CustomHeaders { public string customId { get; set; } public string screenData { get; set; } public string screenSize { get; set; } }
再进行反序列化:
using Newtonsoft.Json; var customHeadersStr = request.Headers["customHeaders"]; var customHeaders = JsonConvert.DeserializeObject<CustomHeaders>(customHeadersStr); var customId = customHeaders.customId;
内容的提问来源于stack exchange,提问作者Sri
相关产品推荐
相关产品推荐

