How to get POST data in WebAPI?

前端 未结 8 1318
天涯浪人
天涯浪人 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

    I had a problem with sending a request with multiple parameters.

    I've solved it by sending a class, with the old parameters as properties.

    <form action="http://localhost:12345/api/controller/method" method="post">
        <input type="hidden" name="name1" value="value1" />
        <input type="hidden" name="name2" value="value2" />
        <input type="submit" name="submit" value="Submit" />
    </form>
    

    Model class:

    public class Model {
        public string Name1 { get; set; }
        public string Name2 { get; set; }
    }
    

    Controller:

    public void method(Model m) {
        string name = m.Name1;
    }
    
    0 讨论(0)
  • 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

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