简体   繁体   English

如何将复杂对象从jQuery ajax调用传递到ASP.NET WebApi GET?

[英]How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

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". ASP.NET控制器方法中的“过滤器”对象为“空”。 If I change it to a POST the filter object is passed correctly. 如果我将其更改为POST,则过滤器对象正确传递。 Is there a way to pass a complex object to a GET? 有没有办法将复杂的对象传递给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,因为会有许多参数使效率低下,很难拥有可选参数,并且即使添加了新参数,方法签名也保持不变。

After finding this StackOverflow question/answer 找到此StackOverflow问题/答案之后

Complex type is getting null in a ApiController parameter 复杂类型在ApiController参数中为null

the [FromBody] attribute on the controller method needs to be [FromUri] since a GET does not have a body. 控制器方法上的[FromBody]属性必须为[FromUri],因为GET没有主体。 After this change the "filter" complex object is passed correctly. 进行此更改后,将正确传递“过滤器”复杂对象。

If you append json data to query string, and parse it later in web api side. 如果将json数据附加到查询字符串,然后稍后在Web api端进行解析。 you can parse complex object. 您可以解析复杂的对象。 It's useful rather than post json object style. 它比发布json对象样式有用。 This is my solution. 这是我的解决方案。

//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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM