How to get POST data in WebAPI?

前端 未结 8 1339
天涯浪人
天涯浪人 2020-11-29 21:32

I\'m sending a request to server in the following form:

http://localhost:12345/api/controller/par1/par2

The request is correctly resolved t

8条回答
  •  暖寄归人
    2020-11-29 22:10

    It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.

    public class MyParameters
    {
        public string a { get; set; } 
        public string b { get; set; }
    }
    
    public MyController : ApiController
    {
        public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }
    }
    

    Then you go to:

    http://localhost:12345/api/MyController?a=par1&b=par2
    

    Reference: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".

    See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

提交回复
热议问题