首页 > 解决方案 > 通过 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 请求。

标签: c#jsonajaxasp.net-mvctypescript

解决方案


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

推荐阅读