从mvc网址中隐藏一个控制器名称,显示其他控制器名称 [英] Hide one controller name from mvc url, show other controller names

查看:137
本文介绍了从mvc网址中隐藏一个控制器名称,显示其他控制器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器,HomeController和ResourcesController. 当请求对HomeController进行操作时,我想从URL中隐藏Home/,但是对于ResourcesController(或任何其他controlelr),我想将控制器名称保留在url中. 例如./Home/产品将是/Produtcs,但/Resources/Banana应该保留/Resources/Banana

I have two controllers, HomeController and ResourcesController. I want to hide the Home/ from the url when action on HomeController is requested, but for ResourcesController (or any other controlelr) I want to keep the controller name in url. E.g. /Home/Products will be /Produtcs, but /Resources/Banana should stay /Resources/Banana

这些是我的路线:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

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

对于家庭控制器,它可以按预期工作,但是对于资源控制器,我得到"404 ...找不到资源"

It works as expected for home controller but for resources controller I get "404... The resource cannot be found"

推荐答案

一种可能的方法是,您可以在global.asax文件中映射所有主页操作.请参见下面的示例代码.

One possible way is you can map all the home page actions within the global.asax file. See the example code below.

例如

    routes.MapRoute(
        "ProdutcsRoute", // Route name
        "Produtcs/{id}", // URL with parameters
        new { controller = "Home", action = "Produtcs", id = UrlParameter.Optional } // Parameter defaults
    );

    routes.MapRoute(
        "AboutRoute", // Route name
        "About/{id}", // URL with parameters
        new { controller = "Home", action = "About", id = UrlParameter.Optional } // Parameter defaults
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );

这篇关于从mvc网址中隐藏一个控制器名称,显示其他控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆