如何更改 URL 中的 ASP.NET MVC 控制器名称? [英] How to Change ASP.NET MVC Controller Name in URL?

查看:30
本文介绍了如何更改 URL 中的 ASP.NET MVC 控制器名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If we have "example_name" we can change it in url using [ActionName("")] So, i want to do this for controller name.

我可以这样做:

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

ControllerName > example_nameController > in URL: "/example_controller"

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

I would like to change controller name like this in URL: "/example-conroller"

推荐答案

您需要使用属性路由,MVC 5 中引入的一个特性.

You need to use Attribute Routing, a feature introduced in MVC 5.

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

Based on your example you should edit your controller as follows:

[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();
    }
}

使用控制器顶部的 RoutePrefix 属性将允许您在整个控制器上定义路由.

Using the RoutePrefix attribute on top of your controller will allow you to define the route on the entire controller.

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

As said before, this feature is available natively in MVC 5, if you are using a previous version of MVC you need to add the following NuGet package: AttributeRouting and add the following using in your controller:

using AttributeRouting;
using AttributeRouting.Web.Mvc;

<小时>如果您有另一个名为 example_name2Controller 的控制器,并且您想添加一个链接到它的超链接,您可以轻松地执行以下操作:


If you have another controller called example_name2Controller and you want to add an hyperlink that link to it you can easily do it as follows:

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

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

You don't need to call an action that will redirect to the example_name2Controller, but if you need to do it in other occasions, you can do it like this:

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

这篇关于如何更改 URL 中的 ASP.NET MVC 控制器名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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