本文介绍了将Url.RouteUrl()与区域中的路由名称一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为旁注,我了解整个控制器名称不明确的问题并且使用了命名空间来使我的路线正常运行,所以我认为这不是问题.

As a side note, I understand the whole ambiguous controller names problem and have used namespacing to get my routes working, so I don't think that is an issue here.

到目前为止,我有我的项目级别控制器,然后是一个具有以下注册的用户区:

So far I have my project level controllers and then a User Area with the following registration:

public class UserAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "User";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "UserHome",
            "User/{id}",
            new { action = "Index", controller = "Home", id = 0 },
            new { controller = @"Home", id = @"\d+" }
        );

        context.MapRoute(
            "UserDefault",
            "User/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

这里有"UserHome"路由,因此我可以允许路由/User/5/User/Home/Index/5一起使用,这看起来更干净.

The "UserHome" route is there so I can allow the route /User/5 vs. /User/Home/Index/5 which looks cleaner IMO.

理想情况下,我想使用Url.RouteUrl("UserHome", new { id = 5 })在其他位置生成路由,但这总是空白或给我一个例外,表明它找不到路由名称,这显然在那里.

Ideally I would like to use Url.RouteUrl("UserHome", new { id = 5 }), to generate the route elsewhere, but this always either comes back blank or gives me an exception saying it cannot find the route name, which is obviously there.

但是,当我使用Url.RouteUrl("UserHome", new { controller = "Home", action = "Index", id = 5 })时,它没有问题.

However when I use Url.RouteUrl("UserHome", new { controller = "Home", action = "Index", id = 5 }) it works no problem.

当路由映射中已经具有默认值时,为什么必须指定动作和控制器?我想念什么?

Why do I have to specify the action and controller when they have defaults already in the route mapping? What am I missing?

推荐答案

我可以确认至少使用.NET 4.5.1和MVC 5.2.2,此行为已修复,并且现在可以与此相同使用Url.RouteUrl("UserHome", new { id = 5 })的确切代码.

I can confirm that with .NET 4.5.1 and MVC 5.2.2 at the minimum, that this behavior has been fixed and now works as is with this same exact code using Url.RouteUrl("UserHome", new { id = 5 }).

这似乎是自发布以来已修复的错误.

It looks like this was a bug that has been fixed since the time of my post.

将其添加为答案,因为尽管TSmith的解决方案可以工作,但由于有修复,您不再需要做额外的工作.

Adding this as the answer since although TSmith's solution would work, you no longer need to do that extra work now that there is a fix.

这篇关于将Url.RouteUrl()与区域中的路由名称一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 03:11