Simple controller which takes POST is not found

2019-03-11 14:16发布

I've made some previous question asking for the help with the problems since I updated MVC4 webapi beta to RC. I got most in order now, but here's one I cannot figure out the reason for yet.

For this simple controller I have one which accepts a POST and one that accepts GET. When I try to run those by sending request from a HTML form, only the GET controller is found while the POST one will return 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>

1条回答
相关推荐>>
2楼-- · 2019-03-11 14:51

Web.API is a little bit 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 posted data:

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

With this change you won't get 404 anymore but output will be always null, because Web.Api requries the posted values in special format (look for the Sending Simple Types section):

Second, the client needs to send the value with the following format:

=value

Specifically, the name portion 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 script...

So recommend that you should 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 froms without modifing your views.

查看更多
登录 后发表回答