【问题标题】:ASP.Net MVC 4 WebAPI Custom RoutingASP.Net MVC 4 WebAPI 自定义路由
【发布时间】:2013-02-12 15:53:03
【问题描述】:

我的 WebAPI 项目中有一个名为 News 的控制器,我有两个名为 Get 的默认操作,用于处理以下 URL:

/api/News

到目前为止,一切都很简单,显然默认路由可以处理这些场景。我接下来想要一个如下所示的 URL:

/api/News/123/Artists

现在我对 ASP.Net MVC 和 WebAPI 来说是相当新鲜的,所以这是我第一次不得不处理路由。我已将默认路由修改为如下所示:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{id}/{action}",
            defaults: new { controller = "News", action = "Get", id = UrlParameter.Optional }

所以我在这里将 {action} 移到了 URL 的末尾,并在我的 News 控制器中添加了一个 Artists 方法。这仍然适用于前两种情况,但在第三种情况下返回 404。

显然路由不适用于 /api/News/123/Artists 但我不知道为什么。

我似乎找不到任何这样的人使用 WebAPI 的例子,这让我觉得我做的事情根本上是错误的。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    问题是,您尝试访问 Web API 但映射 ASP.NET MVC

    这是您需要的映射:

    config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}/{action}",
      defaults: new {controller = "News", action = "Get", id = RouteParameter.Optional}
      );
    

    并且应该在App_Start \ WebApiConfig中完成(如果使用默认模板设置)

    方法示例(在您的新闻 API 控制器中):

    // GET api/values/5
    public string Get(int id)
    {
      return "value " + id;
    }
    
    // GET api/values/5
    [HttpGet]
    public string Artist(int id)
    {
      return "artist " + id;
    }
    

    【讨论】:

    • 啊!你的权利,我立即去了 RouteConfig 类,而不是 WebApiConfig 类。把这归结为一个 WebAPI 新手错误:)
    【解决方案2】:

    AttributeRouting 应该是一个很好的解决方案。可以Nuget安装,文档是here

    一些例子

    public class SampleController : Controller
    {
        [GET("Sample")]
        public ActionResult Index() { /* ... */ }
                        
        [POST("Sample")]
        public ActionResult Create() { /* ... */ }
                        
        [PUT("Sample/{id}")]
        public ActionResult Update(int id) { /* ... */ }
                        
        [DELETE("Sample/{id}")]
        public string Destroy(int id) { /* ... */ }
        
        [Route("Sample/Any-Method-Will-Do")]
        public string Wildman() { /* ... */ }
    
        [GET("", ActionPrecedence = 1)]
        [GET("Posts")]
        [GET("Posts/Index")]
        public ActionResult Index() { /* ... */ }
    
        [GET("Demographics/{state=MT}/{city=Missoula}")]
        public ActionResult Index(string state, string city) { /* ... */ }
    }
    

    custom routing 的效果很好。

    更新

    In asp.net WebApi 2, AttributeRouting is included inside by native.有一些历史,第一个版本asp.net WebApi 1在路由注解方面比较薄弱。

    然后,asp.net WebApi 2 被释放,AttributeRouting 被原生包含。所以,那个开放的项目不再维护了,GitHub page 说。

    In microsoft blog,部分Independent Developer Profile – Tim McCall – Attribute Routing in MVC and Web API 2也说了历史。

    【讨论】:

    【解决方案3】:

    在路由中,Action 是您要路由到的方法上的操作名称。该操作名称应该在方法上使用的属性中。

     [HttpGet]
     [ActionName("CustomAction")]
    public HttpResponseMessage MyNewsFeed(Some params)
    { return Request.CreateResponse(); }
    

    现在你的路线应该是这样的

    routes.MapRoute(
            name: "Default",
            url: "{controller}/{id}/{action}",
            defaults: new { controller = "News", action = "CustomAction", id = UrlParameter.Optional 
    

    如果这有帮助,请告诉我。

    【讨论】:

      猜你喜欢
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多