从URL中删除操作名称并将页面标题添加到URL - Asp.net MVC

时间:2016-12-28 08:44:36

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

我有这样的网址:

http://localhost:17594/Contact/Contact

现在我想这样表现出来:

http://localhost:17594/Contact/Contact-us

RouteConfig:

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

    routes.MapRoute(
        name: "Categories",
        url: "Categories/{id}",
        defaults: new { controller = "Categories", action = "Index", id = UrlParameter.Optional },
        namespaces: new[] { "FinalKaminet.Controllers" }
    );

    routes.MapRoute(
        name: "Contacts",
        url: "{controller}/{title}",
        defaults: new { controller = "Contact", action = "Contact", title = UrlParameter.Optional },
        namespaces: new[] { "FinalKaminet.Controllers" }
    );

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

}

查看

@Html.ActionLink("Contact Us", "Contact" , "Contact" , new { title = "contact-us" } , null)

但我在第63行中遇到使用Categories地图路线的错误。

  

异常详细信息:System.InvalidOperationException:中没有路由   路由表匹配提供的值。

     

来源错误:

     

第62行:@ Html.ActionLink(“وبلاگ”,“”)

     

第63行:@ Html.Action(“MenuCat”,“Home”)

有什么问题?

3 个答案:

答案 0 :(得分:0)

要将网址操作显示为Contact-us(以定义路由),您可以使用属性路由。

[Route("Contact/Contact-us")]
    public ActionResult Contact() { … }

有关更多信息,请参阅msdn。 https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

答案 1 :(得分:0)

试试这个

路线配置文件中:

routes.MapRoute(
        name: "Contacts",
        url: "Contact/{action}/{title}",
        defaults: new { controller = "Contact", action = "Contact", title = UrlParameter.Optional },
        namespaces: new[] { "FinalKaminet.Controllers" }
    );

答案 2 :(得分:0)

您有两种选择。

通过基于约定的路由添加特定路由

routes.MapRoute(
    name: "ContactUs",
    url: "contact/contact-us",
    defaults: new { controller = "Contact", action = "Contact" },
    namespaces: new[] { "FinalKaminet.Controllers" }
);

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

或者在基于约定的路线

之前在RouteConfig中启用属性路由
//enable attribute routing
routes.MapMvcAttributeRoutes();

//other convention-based routes.
routes.MapRoute(....);

并将路径直接应用于控制器和操作。

public class ContactController : Controller {

    //GET contact/contact-us
    [HttpGet]
    [Route("Contact/Contact-us")]
    public ActionResult Contact() { … }

}
相关问题