c# - 通过 GET 请求将 JSON 参数传递给 MVC 控制器
问题描述
我正在尝试将 GET 请求的查询字符串上的一些 JSON 传递给 MVC 控制器,但似乎无法将其作为null
.
Ajax(通过 TypeScript)
$.ajax(url, {
method: 'GET',
data: { 'request': JSON.stringify(this.request) },
dataType: 'json'
})
MVC 控制器
[Route("stuffAndThings/{request?}")]
public async Task<HttpResponseMessage> GetStuff(requestType request)
{
}
因为这是 TypeScript,所以传递的对象是 C# 模型的 TypeScript 表示,包括几个自定义对象
TS类
class requestType {
pageData: PageData;
}
C# 类
public class requestType
{
public PageData pageData { get; set; } = new PageData();
}
查看 devtools 中的请求,它似乎在查询字符串上正确传递,但在控制器上总是以 null 的形式传递。
我错过了什么?
编辑
为了解决一些评论,控制器方法纯粹用于数据检索,并且将来有可能变成 WebAPI 方法,所以如果可能,我想将其保留为 GET 请求。
解决方案
在 MVC 控制器中,您将获取参数作为字符串,因为您已通过 GET 请求将参数作为字符串传递
[Route("stuffAndThings/{request?}")]
public async Task<HttpResponseMessage> GetStuff(string request)
{
}
使requestType
类可序列化,现在在您的方法中,您必须将 json 字符串反序列化为您的对象
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(request)))
{
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(requestType));
requestType requestObj = (requestType)deserializer.ReadObject(ms);
//your code here
}
推荐阅读
- html - 如何禁用 iOS Chrome 密码/信用卡自动填充?
- apache - 如何在 AEM access.log 或 request.log 中打印 http 标头 cookie?
- javascript - 如何在javascript中将String类型的数组转换为数组对象
- winapi - CF_DIBV5 的 Windows 剪贴板 ::GetClipboardData() 导致剪贴板上的图像被修改和损坏?
- swift - SpriteKit 节点穿墙
- java - java.lang.NoClassDefFoundError:解析失败:Landroid/graphics/BlendModeColorFilter;
- java - 如何为方法在接口内部声明并且该接口由两个不同的类实现的方法实现番石榴缓存
- rhel - systemctl 启动服务在 SPEC 文件中不起作用
- javascript - 随着范围滑块的移动计算并显示总数
- javascript - 有没有办法让文本隐藏在输入框中?