【问题标题】:MVC.NET RoutingMVC.NET 路由
【发布时间】:2016-09-30 20:18:36
【问题描述】:

我想在我的 Web Api 中添加一条新路由,它会读取各种 id,然后过滤一堆书。

所以最终的 url 应该是 http://localhost/api/books/1/1/1/1

现在我添加了一条到我的RouteConfig 的路由,如下所示:-

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "BookFilter",
            url: "api/books/{author}/{title}/{genre}/{isbn}",
            defaults: new { controller = "Books", action = "BookFilter" }
        );

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

    }

我还在我的BooksController 中添加了以下内容:-

    [HttpGet]
    public IQueryable<BookDTO> BookFilter(int authorId, int titleId, int genreId, int isbn)
    {
        //filter books here
        return db.Books.ProjectTo<BookDTO>();
    }

但是,当我尝试访问该页面时,我得到了 404。

我需要做什么才能访问我的页面?

感谢您的帮助和时间

【问题讨论】:

  • 知道attribute routing吗?
  • 是的,我有一个想法,只是我有一段时间没有这样做了

标签: asp.net-mvc asp.net-web-api2 url-routing asp.net-mvc-routing asp.net-web-api-routing


【解决方案1】:

Web API 和 MVC 是各自具有不同类型的独立框架。您的路线不起作用的可能原因是您混淆了两者。具体来说,要使其按照您的配置工作,您需要一个 MVC 控制器(即继承 System.Web.Mvc.Controller 的控制器)。

因此,假设您想使用 Web API,正如您的问题所表明的那样,您首先需要确保控制器的正确定义。它应该继承自System.Web.Http.ApiController

public class BooksController : ApiController
{
    [HttpGet]
    public IHttpActionResult BookFilter(string author, string title, string genre, string isbn)
    {
        return Ok("Successful result");
    }
}

接下来,您需要将您的路由放在WebApiConfig.cs 文件中,而不是RouteConfig.cs 文件中。不要忘记从RouteConfig.cs 文件中删除您的路线。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "BookFilter", 
            routeTemplate: "api/books/{author}/{title}/{genre}/{isbn}", 
            defaults: new { controller = "Books", action = "BookFilter" });

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

您还需要确保对GlobalConfiguration.Configure(WebApiConfig.Register); 的调用在您的应用程序启动路径中(默认情况下在Global.asax 中)。

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

【讨论】:

    【解决方案2】:

    确保在您的操作中使用相同的参数名称(例如,将 author 更改为 authorId):

    您也可以在 RouteConfig 中为这些参数指定默认值,如下所示:

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapRoute(
                name: "BookFilter",
                url: "api/books/{authorId}/{titleId}/{genreId}/{isbn}",
                defaults: new { controller = "Books", action = "BookFilter", authorId= UrlParameter.Optional, titleId = UrlParameter.Optional, genreId = UrlParameter.Optional, isbn = UrlParameter.Optional }
            );
    
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
    
        }
    

    控制器:

        [HttpGet]
        public IQueryable<BookDTO> BookFilter(int authorId, int titleId, int genreId, int isbn)
        {
            //filter books here
            return db.Books.ProjectTo<BookDTO>();
        }
    

    【讨论】:

    • 尝试了您的更改,但仍未到达该页面。仍然得到 404
    • 1) 您不需要为每个参数指定默认值。当您不指定默认值时,它会要求 URL 参数(在这种情况下可能更可取)。 2) UrlParameter.Optional 每条路线只能使用 1 次,并且它必须是最右边的参数。 3)这是配置Web API路由的错误地方。见my answer
    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2020-07-18
    相关资源
    最近更新 更多