c# - 网络 API : different way of attribute routing

标签 c# asp.net-web-api

我正在学习网络 API。刚刚浏览了几篇文章,发现属性路由可以用不同的方式完成。

查看使用的代码:

[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。例如,如果您将 RouteHttpGetHttpPost 一起使用,则该路由将通过这些动词可用。

因此,您可以根据自己的需要和喜好进行一些混合。

关于c# - 网络 API : different way of attribute routing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439348/

相关文章:

.net - WCF 服务可以像 WEB API 服务一样模块化吗?

C# 等价于 C++ 回调

c# switch 语句比 vb.net 'case' 更受限制

c# - 替换 ObservableCollection<T> 中的项目时出现 ArgumentOutOfRangeException

c# - 空合并运算符的错误使用?

javascript - 为什么我对 web.api 的请求被长时间运行的 Controller 代码阻止?

c# - 如何注册对数据库的权限并授予 asp.net 样板中的角色

asp.net-web-api - Thinktecture IdentityModel AuthenticationConfiguration Mapping for Cookie - 如何?

asp.net-web-api - asp.net web api 中 DelegatingHandler 的生命周期

c# - Roslyn 内存中代码的静态代码分析