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

后端 未结 2 1112
天涯浪人
天涯浪人 2020-12-15 02:56

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

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

which I

相关标签:
2条回答
  • 2020-12-15 03:37

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-15 03:39

    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.

    0 讨论(0)
提交回复
热议问题