【问题标题】:ASP.NET MVC Attribute & Conventional Routing not workingASP.NET MVC 属性和常规路由不起作用
【发布时间】:2017-01-16 16:27:54
【问题描述】:

我正在尝试配置基于常规和基于属性的路由。

如果我只使用 MVC 中包含的默认常规路由,一切正常。但是如果我添加这个 Route 属性,我会得到一个 404。

这里是 GET 请求 URL:http://localhost:52386/Home/SimpleSearch?searchTerms=test&dateRange=0

这是我在代码中的 RouteAttributes:

[RoutePrefix("Home")] 
public class HomeController : Controller
{
    [Route("SimpleSearch/{searchTerms}/{dateRange}/{page?}")]
    [HttpGet]
    public ActionResult SimpleSearch(string searchTerms, DateRangeEnum dateRange, int page = 1)
    {
       //Code here
    }

}

Route Config 也是这样的:

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

        routes.MapMvcAttributeRoutes();

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

我看不出这个 RouteAttribute 有什么问题,但即使它有问题,为什么它不回退到默认的常规 Route 并工作?

【问题讨论】:

    标签: c# asp.net asp.net-mvc routing url-routing


    【解决方案1】:

    使用属性路由定义,您明确指定了路由模式

    Home/SimpleSearch/{searchTerms}/{dateRange}/{page?}
    

    因此,您应该尝试使用相同的 url 模式访问您的操作方法。

    这应该可行。

     http://localhost:52386/Home/SimpleSearch/test/0
    

    并且模型绑定器将能够将"test" 映射到searchTerms 参数和0 到dateRange 参数。

    当您拥有具有不同模式的属性路由时,您的常规(显式使用查询字符串)将不起作用

    【讨论】:

    • 应该工作,但它没有。它也给了我一个 404 错误。
    • 常规路由确实可以工作..因为当我删除属性路由时,正常的查询字符串获取请求工作正常
    • 它(具有属性路由 url 模式的请求)应该可以工作(我只是复制并粘贴它并验证它)。使用属性路由定义(自定义 url 模式)装饰后,常规路由将不起作用
    • 为什么传统路线不再有效?我都在使用它们,它们都被放入路由字典中,因为我在路由配置中声明了两者。无论如何,我仍然无法让它工作。我工作的唯一方法是如果我将路线中的所有参数设为可选:[Route("SimpleSearch/{searchTerms?}/{dateRange?}/{page?}")]
    • 我刚刚尝试了您任务中的代码,它对我来说效果很好(当我尝试 mysiteName/Home/SimpleSearch/test/0 时)。
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2017-12-20
    • 2023-03-12
    相关资源
    最近更新 更多