ASP.Net MVC 4 WebAPI 自定义路由

7
我有一个名为News的控制器在我的WebAPI项目中,我有两个默认操作名为Get,处理以下URL:
/api/News <- 这将返回新闻列表 /api/News/123 <- 这将返回特定ID的新闻项。
到目前为止都很简单,显然默认路由处理了这些情况。接下来,我希望有一个像这样的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 的示例,这使我认为我正在做一些根本性的错误。

任何帮助将不胜感激。

3个回答

8
问题在于,您尝试访问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;
}

1
啊!你说得对,我立刻去了RouteConfig类而不是WebApiConfig类。把这归咎于WebAPI新手错误 :) - Lee Dale

3

AttributeRouting是一个不错的解决方案。它可以通过Nuget安装,文档在这里

一些例子

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) { /* ... */ }
}

关于自定义路由,它的表现非常好。

更新

在 asp.net WebApi 2 中,AttributeRouting 已经被内置了。 它有一些历史,第一个版本 asp.net WebApi 1 在路由注释方面较弱。

然后,asp.net WebApi 2 发布了,AttributeRouting 被内置了。因此,在GitHub页面中说,该开放项目不再维护。

在微软博客中,部分内容 Independent Developer Profile – Tim McCall – Attribute Routing in MVC and Web API 2 也谈到了历史。


1
因为建议使用第三方解决方案来解决框架中的一个简单误解而被踩。实际上,它可以很好地开箱即用。 - Lee Dale
在ASP.NET WebApi 2中,包含了属性路由。 - AechoLiu

1

在路由中,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 

让我知道这是否有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接