在区域

时间:2018-02-26 18:13:29

标签: asp.net-mvc routes url-routing asp.net-mvc-routing asp.net-mvc-areas

我在更改路由后无法呈现URL地址。

路由配置

public class AccountArea : AreaRegistration
{
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Account",
            "Account/{controller}/{action}/{id}",
            new { controller = "User", action = "Index", id = UrlParameter.Optional },
            namespaces:  new[] {
                "Application.Controllers.Account"
            }
        );
    }

    public override string AreaName => "AccountArea";
}

public class FrontArea : AreaRegistration
{
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Front",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces:  new[] {
                "Application.Controllers.Front"
            }
        );
    }

    public override string AreaName => "FrontArea";
}

RouteConfig

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

控制器

// on folder Controllers/Front/
namespace Application.Controllers.Front
class HomeController : Controller
{
   ActionResult Index(){ ... }
}

// on folder Controllers/Account/
Application.Controllers.Account
class UserController : Controller
{
   ActionResult Index(){...}
}

我已更改路由,因为我想将控制器分为2个子文件夹,Front和Account。

此配置允许我将应用程序分为两部分,使用URL地址区分。

localhost/Home/Index [namespace: Application.Controllers.Front]
localhost/Account/User/Index- [namespace: Application.Controllers.Account] 
输入地址到浏览器后

localhost/Home/Index - will start method Index from HomeController
localhost/Account/User/Index - will start method Index from UserController

在网址localhost/Home/Index上显示问题,我尝试呈现属于localhost/Account/User/Index的网址。

当我使用@Url.Action("Index","User")时,将呈现地址,但网址中没有“帐户”前缀。

  

我收到:/User/Index

     

但是,我希望:/Account/User/Index

反之亦然,localhost/Account/User/Index我无法呈现属于localhost/Home/Index的正确网址。

我可以使用Url.RouteUrl来解决这个问题

@Url.RouteUrl("Account", new {controller = "User", account = "Index"} )

但是,这需要路由名称,我不想提供。

0 个答案:

没有答案