复杂类型在 ApiController 参数中变空 [英] Complex type is getting null in a ApiController parameter
问题描述
我不知道为什么我的参数ParametroFiltro Filtro"变空了,其他参数page"和pageSize"变好了.
I don´t know why my parameter "ParametroFiltro Filtro" is getting null, the other parameters "page" and "pageSize" is getting OK.
public class ParametroFiltro
{
public string Codigo { get; set; }
public string Descricao { get; set; }
}
我的 ApiController Get 方法:
My ApiController Get method:
public PagedDataModel<ParametroDTO> Get(ParametroFiltro Filtro, int page, int pageSize)
我的ajax调用:
var fullUrl = "/api/" + self.Api;
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Filtro: { Codigo: '_1', Descricao: 'TESTE' }, page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
推荐答案
您正在尝试使用 GET
方法发送复杂对象.失败的原因是 GET
方法不能有主体,并且所有值都被编码到 URL 中.您可以使用 [FromUri]
来完成这项工作,但首先您需要更改您的客户端代码:
You are trying to send a complex object with GET
method. The reason this is failing is that GET
method can't have a body and all the values are being encoded into the URL. You can make this work by using [FromUri]
, but first you need to change your client side code:
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Codigo: '_1', Descricao: 'TESTE', page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
这样[FromUri]
将能够直接从 URL 中获取复杂的对象属性,如果您像这样更改操作方法:
This way [FromUri]
will be able to pick up your complex object properties directly from the URL if you change your action method like this:
public PagedDataModel<ParametroDTO> Get([FromUri]ParametroFiltro Filtro, int page, int pageSize)
您之前的方法宁愿使用可以有正文的 POST
方法(但您仍然需要使用 JSON.stringify()
将正文格式化为 JSON).
Your previous approach would rather work with POST
method which can have a body (but you would still need to use JSON.stringify()
to format body as JSON).
这篇关于复杂类型在 ApiController 参数中变空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!