简体   繁体   中英

Calling Web API 2 with Get is OK but fails with Post

I am able to invoke Web Api 2 , from static html form with get as below.

Web API:

public class WebServiceController : ApiController
{
    [HttpGet]
    [Route("api/WebService")]
    public IHttpActionResult Post(string FirstName, string Surname)
    { 
        //work
        return StatusCode(HttpStatusCode.OK);
    }
}

HTML Form:

<form action="http://localhost:27020/api/WebService/" method="get">
    <input type="text" name="FirstName" id="FirstName" />
    <input type="text" name="Surname" id="Surname" />
    <input type="submit" />
</form>

When I switch from get to post request with method="post" and [HttpPost] I am getting the screenshot below on Chrome:

在此处输入图片说明

What am I doing wrong?

WebAPI can't read each method parameter independently. You'll have to encapsulate them:

public class WebServiceController : ApiController
{
    [HttpGet]
    [Route("api/WebService")]
    public IHttpActionResult Post(MyRequest request)
    { 
        //work
        return StatusCode(HttpStatusCode.OK);
    }
}

public class MyRequest
{
    public string FirstName { get; set; }
    public string Surname { get; set; }
}

It is always a good practice to change web api route which is

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

to

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

after it you will not require to follow get put and post, you can use full name just like MVC routing. eg. http://yourhost/api/WebService/your_action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM