C# 复杂类型在 ApiController 参数中变空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12916340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Complex type is getting null in a ApiController parameter
提问by will
I don′t know why my parameter "ParametroFiltro Filtro" is getting null, the other parameters "page" and "pageSize" is getting OK.
我不知道为什么我的参数“ParametroFiltro Filtro”变空了,其他参数“page”和“pageSize”变好了。
public class ParametroFiltro
{
public string Codigo { get; set; }
public string Descricao { get; set; }
}
My ApiController Get method:
我的 ApiController Get 方法:
public PagedDataModel<ParametroDTO> Get(ParametroFiltro Filtro, int page, int pageSize)
My ajax call:
我的 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);
}
});
采纳答案by tpeczek
You are trying to send a complex object with GETmethod. The reason this is failing is that GETmethod 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:
您正在尝试使用GET方法发送复杂对象。失败的原因是GET方法不能有主体,并且所有值都被编码到 URL 中。您可以使用 来完成这项工作[FromUri],但首先您需要更改您的客户端代码:
$.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);
}
});
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:
[FromUri]如果您像这样更改操作方法,则这种方式将能够直接从 URL 中获取您的复杂对象属性:
public PagedDataModel<ParametroDTO> Get([FromUri]ParametroFiltro Filtro, int page, int pageSize)
Your previous approach would rather work with POSTmethod which can have a body (but you would still need to use JSON.stringify()to format body as JSON).
您之前的方法宁愿使用POST可以有主体的方法(但您仍然需要使用JSON.stringify()将主体格式化为 JSON)。
回答by Shyju
Provide the contentTypeproperty when you make the ajax call. Use JSON.stringifymethod to build the JSON data to post. change the type to POSTand MVC Model binding will bind the posted data to your class object.
contentType进行 ajax 调用时提供该属性。使用JSON.stringify方法构建要发布的 JSON 数据。将类型更改为POSTMVC 模型绑定会将发布的数据绑定到您的类对象。
var filter = { "Filtro": { "Codigo": "_1", "Descricao": "TESTE" },
"page": "1", "pageSize": "10" };
$.ajax({
url: fullUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(filter),
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
回答by Bes Ley
If you append json data to query string, and parse it later in web api side. you can parse complex object too. It's useful rather than post json object, espeicaly in some special httpget requirement case.
如果您将 json 数据附加到查询字符串,然后在 web api 端解析它。你也可以解析复杂的对象。它比 post json 对象更有用,尤其是在某些特殊的 httpget 需求情况下。
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
回答by graphicdivine
It's also possible to access POST variables via a Newtonsoft.Json.LinqJObject.
也可以通过Newtonsoft.Json.LinqJObject访问 POST 变量。
For example, this POST:
例如,这个帖子:
$.ajax({
type: 'POST',
url: 'URL',
data: { 'Note': note, 'Story': story },
dataType: 'text',
success: function (data) { }
});
Can be accessed in an APIController like so:
可以像这样在 APIController 中访问:
public void Update([FromBody]JObject data)
{
var Note = (String)data["Note"];
var Story = (String)data["Story"];
}

