c# - 通过更改 Razor 中的 url 获取 View

标签 c# asp.net .net razor routes

我的 asp.net mvc4 应用程序中的文件 RouteConfig.cs 有问题:

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

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

            routes.MapRoute(
               name: "Admin",
               url: "Admin",
               defaults: new { controller = "Home", action = "Administration" }
           );
        }

home Controller 中:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
         return View();
        }

        public ActionResult Administration()
        {
            return View();
        }

并添加了 View :

views

但是当我将 http://localhost:61961/Admin 作为 url 时,找不到 View 。

为什么会这样?我该如何解决?

最佳答案

路由配置是有序的。请将您的管理配置移动到 RegisterRoutes 的顶部。

现在你会被映射到

Controller: admin
View: index

因为您的默认路由捕获您的 localhost:{port}/admin

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

    routes.MapRoute(
       name: "Admin",
       url: "Admin",
       defaults: new { controller = "Home", action = "Administration" }
    );

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

关于c# - 通过更改 Razor 中的 url 获取 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17144379/

相关文章:

c# - YASR - 另一个搜索和替换问题

c# - 在标签中显示多行文本框文本之间的空格

c# - C#如何获取声音输入的名称

c# - 如何解析包含引号的字符串

c# - 如何计算数组的长度而不包括 NULL?

.net - 忽略 DataContractSerializer 中的字段顺序

c# - 将 ~280 个控件从 visible=true 更改为 visible=false 大约需要 8-9 秒(太长)

c# - 如何不序列化默认值

asp.net - 在哪里保存 Web 应用程序的类

javascript - 使用 javascript 在 HTMLInput 的字符串上添加一个字符