Simple controller that accepts POST not found

I did some previous questions asking for help with the problems, since I upgraded MVC4 webapi beta to RC. I got the most in order, but here I still can not understand the reason.

For this simple controller, I have one that accepts POST and one that accepts GET. When I try to run them by sending a request from an HTML form, only the GET controller will be found, while POST returns me the following error.

{ "Message": "No HTTP resource was found that matches the request URI 'http://localhost/webapi/api/play/test'.", "MessageDetail": "No action was found on the controller 'Play' that matches the name 'test'." } 

Why is the POST controller not found?

Controllers

 public class PlayController : ApiController { [HttpPost] // not found public string Test(string output) { return output; } [HttpGet] // works public string Test2(string output) { return output; } } 

HTML form

 <form action="http://localhost/webapi/api/play/test" method="post"> <input type="text" name="output" /> <input type="submit" name="submit" /> </form> <form action="http://localhost/webapi/api/play/test2" method="get"> <input type="text" name="output" /> <input type="submit" name="submit" /> </form> 
+43
html-form asp.net-web-api asp.net-mvc-4
Sep 02
source share
1 answer

The Web.API is a little picky when you want to post "simple" values.

You need to use the [FromBody] attribute to signal that the value is not coming from the URL, but from the published data:

 [HttpPost] public string Test([FromBody] string output) { return output; } 

With this change, you will no longer get 404, but the output will always be zero, because Web.Api requires the published values ​​in a special format (look for the "Simple Types" section):

Secondly, the client needs to send a value in the following format:

=value

In particular, part of the name of the name / value pair must be empty for a simple type. Not all browsers support this for HTML forms, but you create this format in a script ...

Therefore, we recommend that you create a model type:

 public class MyModel { public string Output { get; set; } } [HttpPost] public string Test(MyModel model) { return model.Output; } 

Then it will work with your sample without changing your ideas.

+87
Sep 02 '12 at 15:59
source share



All Articles