我正在学习网络 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 属性来定义 Action 的路由。
再看一遍
[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动词来定义路由。
那么请告诉我哪种方法是正确的?
另一个问题,通过属性例程我们可以给 Action 起不同的名字,那么什么时候应该使用 Action 名称属性给 Action 起不同的名字?
当我们可以通过属性路由更改 Action 名称时,为什么还要使用 Action 名称属性为 Action 赋予不同的名称?
最佳答案
[Route]
向外界公开一个 Action 。它将操作名称(方法名称)作为路由的名称。它可以使用 RoutePrefix
或 Controller 名称来构造 URL。
如果您为 [Route(template)]
提供一个值,则该(相对)URL 用于构造操作可用的 URL。
由于默认情况下只能通过GET
访问路由,因此您可以以相同的方式使用HttpGet(template)
和Route
。例如,如果您将 Route
与 HttpGet
和 HttpPost
一起使用,则该路由将通过这些动词可用。
因此,您可以根据自己的需要和喜好进行一些混合。
关于c# - 网络 API : different way of attribute routing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439348/