Pass an array of integers to ASP.NET Web API?

前端 未结 17 2012
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:40

I have an ASP.NET Web API (version 4) REST service where I need to pass an array of integers.

Here is my action method:



        
17条回答
  •  不知归路
    2020-11-22 05:31

    Make the method type [HttpPost], create a model that has one int[] parameter, and post with json:

    /* Model */
    public class CategoryRequestModel 
    {
        public int[] Categories { get; set; }
    }
    
    /* WebApi */
    [HttpPost]
    public HttpResponseMessage GetCategories(CategoryRequestModel model)
    {
        HttpResponseMessage resp = null;
    
        try
        {
            var categories = //your code to get categories
    
            resp = Request.CreateResponse(HttpStatusCode.OK, categories);
    
        }
        catch(Exception ex)
        {
            resp = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
        }
    
        return resp;
    }
    
    /* jQuery */
    var ajaxSettings = {
        type: 'POST',
        url: '/Categories',
        data: JSON.serialize({Categories: [1,2,3,4]}),
        contentType: 'application/json',
        success: function(data, textStatus, jqXHR)
        {
            //get categories from data
        }
    };
    
    $.ajax(ajaxSettings);
    

提交回复
热议问题