我试图将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#class
public class requestType
{
public PageData pageData { get; set; } = new PageData();
}
查看devtools中的请求,它似乎正在查询字符串上正确传递,但总是在控制器上以null形式传递。
我错过了什么?
修改
为了解决几个注释,控制器方法纯粹用于数据检索,并且将来有可能转变为WebAPI方法,因此我希望尽可能将其保留为GET请求。 / p>
答案 0 :(得分:0)
在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
}
答案 1 :(得分:-2)
Json.Stringfy以字符串形式转换您的请求,而在控制器中您使用特定类型获取。因此,要使用strin g而不是 RequestType 来获得正确的结果更新。
如果仍然面临问题,请与我联系。 I am here
如果有帮助,请回复或喜欢。