C# 如何将复杂对象从 jQuery ajax 调用传递给 ASP.NET WebApi GET?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15814160/
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
How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?
提问by ChrisP
I have the following complex object in JavaScript which contains filter options
我在 JavaScript 中有以下复杂对象,其中包含过滤器选项
var filter={caseIdentifiter:'GFT1',userID:'2'};
which I want to pass to an ASP.NET MVC4 WebApi controller GET
我想传递给 ASP.NET MVC4 WebApi 控制器 GET
[HttpGet]
public IEnumerable<JHS.Repository.ViewModels.CaseList> Get([FromBody]Repository.InputModels.CaseListFilter filter)
{
try
{
return Case.List(filter);
}
catch (Exception exc)
{
//Handle exception here...
return null;
}
}
using an jQuery ajax call
使用 jQuery ajax 调用
var request = $.ajax({
url: http://mydomain.com/case,
type: 'GET',
data: JSON.stringify(filter),
contentType: 'application/json; charset=utf-8',
cache: false,
dataType: 'json'
});
The "filter" object in the ASP.NET controller method is "null". If I change it to a POST the filter object is passed correctly. Is there a way to pass a complex object to a GET?
ASP.NET 控制器方法中的“过滤器”对象为“空”。如果我将其更改为 POST,则过滤器对象将正确传递。有没有办法将复杂对象传递给 GET?
I do not want to separate out the parameters to the URL as there will be a number of them which would make it inefficient, it would be hard to have optional parameters, and this way the method signature stays constant even if new parameters are added.
我不想将 URL 中的参数分开,因为会有很多参数会导致效率低下,很难有可选参数,这样即使添加了新参数,方法签名也保持不变。
采纳答案by ChrisP
After finding this StackOverflow question/answer
找到这个 StackOverflow 问题/答案后
Complex type is getting null in a ApiController parameter
the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. After this change the "filter" complex object is passed correctly.
控制器方法上的 [FromBody] 属性需要是 [FromUri],因为 GET 没有主体。在此更改后,“过滤器”复杂对象正确传递。
回答by Bes Ley
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
如果您将 json 数据附加到查询字符串,然后在 web api 端解析它。您可以解析复杂的对象。它比 post json 对象样式有用。这是我的解决方案。
//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;
}
}