【发布时间】:2017-11-10 09:11:23
【问题描述】:
我正在学习 web api。刚刚浏览了几篇文章,发现属性路由可以通过不同的方式完成。
- https://www.codeproject.com/Articles/774807/Attribute-Routing-in-ASP-NET-MVC-WebAPI
- http://www.c-sharpcorner.com/UploadFile/b1df45/web-api-route-and-route-prefix-part-2/
- https://www.codeproject.com/Articles/999691/RESTful-Day-sharp-Custom-URL-Re-Writing-Routing-us
查看使用的代码:
[RoutePrefix("Movie")]
public class HomeController : Controller
{
//Route: Movie/Index
[Route]
public ActionResult Index()
{
ViewBag.Message = "You are in Home Index";
return View();
}
//Route: NewRoute/About
[Route("~/NewRoute/About")]
public ActionResult About()
{
ViewBag.Message = "You successfully reached NEWRoute/About route";
return View();
}
}
在上面的例子中作者使用 Route 属性来定义动作的路由。
再看一次
[GET("productid/{id?}")]
public HttpResponseMessage Get(int id)
{
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
}
这里作者没有使用路由属性,而是使用http动词来定义路由。
那么告诉我哪种方法是正确的?
另一个问题是,我们可以通过属性例程为动作赋予不同的名称,那么何时应该使用动作名称属性为动作赋予不同的名称?
当我们可以通过属性路由更改动作名称时,为什么要使用动作名称属性为动作赋予不同的名称?
【问题讨论】:
-
你也可以使用[HttpGet]属性来定义http动词。我使用它和 [Route()] 是因为我在路由中有操作方法名称,imo 提供了最好的可读性但确实很混乱。
标签: c# asp.net-web-api