是否可以仅使用Route属性提供有效的ASP.NET Controller路由?

时间:2019-04-22 11:52:20

标签: asp.net asp.net-web-api

我创建了一个示例asp.net mvc5 webapi应用程序,并且路由存在问题。 我有一个用[Route(“ dummyset”)]属性修饰的DummyController,我认为足以注册它。

    [HttpPost]
    [Route("dummyset")]
    public IHttpActionResult DummySet([FromBody] DummyModel data)
    {
    }

但是,它不起作用。添加这段代码后:

        routes.MapHttpRoute(
        name: "DummySET",
        routeTemplate: "api/dummy/dummyset",
        defaults: new { Controller = "Dummy", action = "DummySet", method = "POST" }
        );

在WebApiConfig.cs中,一切正常。

我真的必须在这两个地方注册吗?有没有更简单的方法来实现这一目标?当端点的数量增加到一定数量时,可能会在以后保持这种状态成为噩梦。

2 个答案:

答案 0 :(得分:1)

在ASP.NET Web API中,框架使用路由表来确定要调用的操作。

这在这里被称为Convention-based routing,它是必需的。

routes.MapHttpRoute(
        name: "DummySET",
        routeTemplate: "api/dummy/dummyset",
        defaults: new { Controller = "Dummy", action = "DummySet", method = "POST" }
        );

这个叫做Attribute Routing

 [HttpPost]
 [Route("dummyset")]
 public IHttpActionResult DummySet([FromBody] DummyModel data)
 {
 }

如果将以上几行更改为以下代码段并删除属性路由,则应该可以使用。

routes.MapHttpRoute(
    name: "DummySET",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

答案 1 :(得分:0)

在这样的路由表中启用它

public class RouteConfig {

    public static void RegisterRoutes(RouteCollection routes) {            
        //enable attribute routing
        routes.MapMvcAttributeRoutes();

        // After enabling routing following lines shouldn't be needed.
        // convention-based routes
        // routes.MapRoute(
        //     name: "DummySET",
        //     routeTemplate: "api/dummy/dummyset",
        //     defaults: new { Controller = "Dummy", action = "DummySet", method = "POST" }
        // );

        //default routes
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = "" }
        );
    }
}