0

我正在尝试在新项目中使用属性路由,但无法使其正常工作。

这是我到目前为止所拥有的:

[RoutePrefix("Product")]
public class ProductController : Controller
{

    [Route("{id}/{title}", Name = "Product Details")]
    public ActionResult Index(int id = 0, string title = "")
    {
        Product p = Product.Get(id);

        return View(p);
    }
}

这是我的 RouteConfig.cs :

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

        //routes.MapRoute(
        //    "Product Details",
        //    "Product/{id}/{title}",
        //    new { controller = "Product", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional }
        //);

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


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



    }
}

如果我删除路由属性并取消注释我的 RouteConfig.cs 中的第一条路由,它可以正常工作,但我想坚持使用路由属性。

知道为什么它不能正常工作吗?

我要使用的 URL 是:http ://www.mydomain.com/Product/12345/ProductName

编辑,这是我的 Application_Start()

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleMobileConfig.RegisterBundles(BundleTable.Bundles);

}
4

1 回答 1

0

看起来它把它{id}当作一个动作。

尝试这个:

[Route("{id:int}/{title}", Name = "Product Details")]

或这个

[Route("Product/{id}/{title}", Name = "Product Details")]
于 2014-03-11T05:42:43.853 回答