【发布时间】:2013-08-05 17:15:22
【问题描述】:
让我们有一个测试模型。
public class TestRequestModel
{
public string Text { get; set; }
public int Number { get; set; }
}
我希望此服务能够接受以下请求:
- GET /test?Number=1234&Text=MyText
- POST /test 带有标题:Content-Type:application/x-www-form-urlencoded 和正文:Number=1234&Text=MyText
- POST /test 带有标题:Content-Type: application/json 和正文:{"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 路由,我相信它们是邪恶的。
有没有办法避免使用两种方法和/或 DefaultPost 路由?
【问题讨论】:
-
我认为您添加了太多代码,请查看生成的默认项目。你不需要你的属性或特殊路线来做你正在做的事情。此外,不同的动词表示不同的内涵,
GET用于访问数据,POST用于创建新数据。
标签: c# asp.net-web-api