c# - 如何更改 URL 中的 ASP.NET MVC Controller 名称?

标签 c# asp.net-mvc url controller

如果我们有 "example_name",我们可以使用 [ActionName("")] 在 url 中更改它所以,我想为 Controller 名称执行此操作。

我能做到:

ControllerName > example_nameController> 在 URL 中:"/example_controller"

我想在 URL 中像这样更改 Controller 名称:"/example-conroller"

最佳答案

您需要使用 Attribute Routing ,MVC 5 中引入的功能。

根据您的示例,您应该按如下方式编辑您的 Controller :

[RoutePrefix("example-name")]
public class example_nameController : Controller
{
    // Route: example-name/Index
    [Route]
    public ActionResult Index()
    {
        return View();
    }

    // Route: example-name/Contact
    [Route]
    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
}

在 Controller 顶部使用 RoutePrefix 属性将允许您在整个 Controller 上定义路由。

如前所述,此功能在 MVC 5 中原生可用,如果您使用的是以前版本的 MVC,则需要添加以下 NuGet 包:AttributeRouting并在您的 Controller 中使用添加以下内容:

using AttributeRouting;
using AttributeRouting.Web.Mvc;


如果您有另一个名为 example_name2Controller 的 Controller ,并且您想要添加一个链接到它的超链接,您可以按如下方式轻松完成:

@Html.ActionLink("Go to example-name2", "Index", "example_name2");

您不需要调用将重定向到 example_name2Controller 的操作,但如果您需要在其他场合执行此操作,您可以这样做:

public ActionResult RedirectToExample_Name2Controller()
{
    return RedirectToAction("Index", "example_name2");
}

关于c# - 如何更改 URL 中的 ASP.NET MVC Controller 名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33344450/

相关文章:

路径中的 C# 反斜杠

c# - 使用 response.write 打开 byte[] pdf 文件(服务器端操作不起作用

c# - 当我重命名一个类时,出现反序列化错误。如何解决?

javascript - 如何将修改后的数据从双列表框传递到 Controller ?

wordpress - 自定义帖子类型 slug 和永久链接问题 - SEO 和结构

c# - 通过 .exe 文件名杀死一些进程

asp.net-mvc - ASP.NET MVC 术语让我感到困惑 - 为什么是 'ViewModel' ?

c# - Web.config 中的 <pages validateRequest ="false"/> 仍然重要吗?

Android Market 应用程序网址?

javascript - 加载 URL + JavaScript 操作