テストモデルを用意しましょう。
public class TestRequestModel
{
public string Text { get; set; }
public int Number { get; set; }
}
このサービスで次の要求を受け入れることができるようにしたいと考えています。
- GET /test?Number=1234&Text=MyText
- POST /test with header: Content-Type: application/x-www-form-urlencoded and body: Number=1234&Text=MyText
- POST /test with header: Content-Type: application/json and body: {"Text":"Provided!","Number":9876}
ルートは次のように構成されます。
_config.Routes.MapHttpRoute(
"DefaultPost", "/{controller}/{action}",
new { action = "Post" },
new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
_config.Routes.MapHttpRoute(
"The rest", "/{controller}/{action}",
defaults: new { action = "Get" });
私のコントローラーは次のようになります。
public class TestController : ApiController
{
[HttpGet]
public TestResponseModel Get([FromUri] TestRequestModel model)
{
return Do(model);
}
[HttpPost]
public TestResponseModel Post([FromBody] TestRequestModel model)
{
return Do(model);
}
(...)
これは定型コードの許容量のように思えますが、可能であれば避けたいと思います。
余分なルートを持つことも理想的ではありません。私は MVC/WebAPI ルートを恐れており、悪だと信じています。
2 つのメソッドやDefaultPostルートを避ける方法はありますか?