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

105,022

Solution 1

After finding this StackOverflow question/answer

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.

Solution 2

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.

//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;
    }
}
Share:
105,022
ChrisP
Author by

ChrisP

Updated on January 25, 2020

Comments

  • ChrisP
    ChrisP over 4 years

    I have the following complex object in JavaScript which contains filter options

    var filter={caseIdentifiter:'GFT1',userID:'2'};
    

    which I want to pass to an ASP.NET MVC4 WebApi controller 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

    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?

    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.

  • Sudhanshu Mishra
    Sudhanshu Mishra about 8 years
    No offence, but this looks very hacky and hard to test