asp.net-mvc Asp.Net MVC:如何在我的 url 中启用破折号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 22:44:06  来源:igfitidea点击:

Asp.Net MVC: How do I enable dashes in my urls?

asp.net-mvc

提问by Jim Geurts

I'd like to have dashes separate words in my URLs. So instead of:

我想在我的 URL 中用破折号分隔单词。所以而不是:

/MyController/MyAction

I'd like:

我想要:

/My-Controller/My-Action

Is this possible?

这可能吗?

回答by ChadT

You can use the ActionName attribute like so:

您可以像这样使用 ActionName 属性:

[ActionName("My-Action")]
public ActionResult MyAction() {
    return View();
}

Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods.

请注意,您随后需要调用您的视图文件“My-Action.cshtml”(或适当的扩展名)。您还需要在任何 Html.ActionLink 方法中引用“my-action”。

There isn't such a simple solution for controllers.

控制器没有这么简单的解决方案。

Edit: Update for MVC5

编辑:MVC5 更新

Enable the routes globally:

全局启用路由:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapMvcAttributeRoutes();
    // routes.MapRoute...
}

Now with MVC5, Attribute Routing has been absorbed into the project. You can now use:

现在使用 MVC5,属性路由已经被吸收到项目中。您现在可以使用:

[Route("My-Action")]

On Action Methods.

关于行动方法。

For controllers, you can apply a RoutePrefixattribute which will be applied to all action methods in that controller:

对于控制器,您可以应用一个RoutePrefix属性,该属性将应用于该控制器中的所有操作方法:

[RoutePrefix("my-controller")]

One of the benefits of using RoutePrefixis URL parameters will also be passed down to any action methods.

使用的好处之一RoutePrefix是 URL 参数也将传递给任何操作方法。

[RoutePrefix("clients/{clientId:int}")]
public class ClientsController : Controller .....

Snip..

剪..

[Route("edit-client")]
public ActionResult Edit(int clientId) // will match /clients/123/edit-client

回答by Andrew

You could create a custom route handler as shown in this blog:

您可以创建一个自定义路由处理程序,如本博客所示:

http://blog.didsburydesign.com/2010/02/how-to-allow-hyphens-in-urls-using-asp-net-mvc-2/

http://blog.didsburydesign.com/2010/02/how-to-allow-hyphens-in-urls-using-asp-net-mvc-2/

public class HyphenatedRouteHandler : MvcRouteHandler{
        protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
        {
            requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
            return base.GetHttpHandler(requestContext);
        }
    }

...and the new route:

...以及新路线:

routes.Add(
            new Route("{controller}/{action}/{id}", 
                new RouteValueDictionary(
                    new { controller = "Default", action = "Index", id = "" }),
                    new HyphenatedRouteHandler())
        );

A very similar question was asked here: ASP.net MVC support for URL's with hyphens

这里问了一个非常相似的问题:ASP.net MVC support for URL's with hyphens

回答by Ata S.

I've developed an open source NuGet libraryfor this problem which implicitly converts EveryMvc/Url to every-mvc/url.

我为此问题开发了一个开源NuGet 库,它将 EveryMvc/Url 隐式转换为 every-mvc/url。

Uppercase urls are problematic because cookie paths are case-sensitive, most of the internet is actually case-sensitive while Microsoft technologies treats urls as case-insensitive. (More on my blog post)

大写 url 有问题,因为 cookie 路径区分大小写,大多数互联网实际上是区分大小写的,而 Microsoft 技术将 url 视为不区分大小写。(更多关于我的博客文章

NuGet Package: https://www.nuget.org/packages/LowercaseDashedRoute/

NuGet 包:https: //www.nuget.org/packages/LowercaseDashedRoute/

To install it, simply open the NuGet window in the Visual Studio by right clicking the Project and selecting NuGet Package Manager, and on the "Online" tab type "Lowercase Dashed Route", and it should pop up.

要安装它,只需通过右键单击项目并选择 NuGet 包管理器,在 Visual Studio 中打开 NuGet 窗口,然后在“在线”选项卡上键入“小写虚线路由”,它就会弹出。

Alternatively, you can run this code in the Package Manager Console:

或者,您可以在包管理器控制台中运行此代码

Install-Package LowercaseDashedRoute

Install-Package LowercaseDashedRoute

After that you should open App_Start/RouteConfig.cs and comment out existing route.MapRoute(...) call and add this instead:

之后,您应该打开 App_Start/RouteConfig.cs 并注释掉现有的 route.MapRoute(...) 调用并添加以下内容:

routes.Add(new LowercaseDashedRoute("{controller}/{action}/{id}",
  new RouteValueDictionary(
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
    new DashedRouteHandler()
  )
);

That's it. All the urls are lowercase, dashed, and converted implicitly without you doing anything more.

就是这样。所有的 url 都是小写、虚线和隐式转换的,你不需要做任何更多的事情。

Open Source Project Url: https://github.com/AtaS/lowercase-dashed-route

开源项目网址:https: //github.com/AtaS/lowercase-dashed-route

回答by Daniel Eagle

Here's what I did using areas in ASP.NET MVC 5 and it worked liked a charm. I didn't have to rename my views, either.

这是我在 ASP.NET MVC 5 中使用区域所做的事情,它的工作非常吸引人。我也不必重命名我的视图。

In RouteConfig.cs, do this:

在 RouteConfig.cs 中,执行以下操作:

 public static void RegisterRoutes(RouteCollection routes)
    {
        // add these to enable attribute routing and lowercase urls, if desired
        routes.MapMvcAttributeRoutes();
        routes.LowercaseUrls = true;

        // routes.MapRoute...
    }

In your controller, add this before your class definition:

在您的控制器中,在类定义之前添加以下内容:

[RouteArea("SampleArea", AreaPrefix = "sample-area")]
[Route("{action}")]
public class SampleAreaController: Controller
{
    // ...

    [Route("my-action")]
    public ViewResult MyAction()
    {
        // do something useful
    }
}

The URL that shows up in the browser if testing on local machine is: localhost/sample-area/my-action. You don't need to rename your view files or anything. I was quite happy with the end result.

如果在本地机器上测试,浏览器中显示的 URL 是:localhost/sample-area/my-action。你不需要重命名你的视图文件或任何东西。我对最终结果非常满意。

After routing attributes are enabled you can delete any area registration files you have such as SampleAreaRegistration.cs.

启用路由属性后,您可以删除您拥有的任何区域注册文件,例如 SampleAreaRegistration.cs。

This articlehelped me come to this conclusion. I hope it is useful to you.

这篇文章帮助我得出了这个结论。我希望它对你有用。

回答by Jim Geurts

Asp.Net MVC 5 will support attribute routing, allowing more explicit control over route names. Sample usage will look like:

Asp.Net MVC 5 将支持属性路由,允许对路由名称进行更明确的控制。示例用法如下所示:

[RoutePrefix("dogs-and-cats")]
public class DogsAndCatsController : Controller
{
    [HttpGet("living-together")]
    public ViewResult LivingTogether() { ... }

    [HttpPost("mass-hysteria")]
    public ViewResult MassHysteria() { }
}

To get this behavior for projects using Asp.Net MVC prior to v5, similar functionality can be found with the AttributeRouting project(also available as a nuget). In fact, Microsoft reached out to the author of AttributeRouting to help them with their implementation for MVC 5.

为了在 v5 之前使用 Asp.Net MVC 的项目获得这种行为,可以在AttributeRouting 项目(也可作为 nuget)中找到类似的功能。事实上,微软联系了 AttributeRouting 的作者,以帮助他们实现 MVC 5。

回答by Haacked

You could write a custom route that derives from the Route class GetRouteData to strip dashes, but when you call the APIs to generate a URL, you'll have to remember to include the dashes for action name and controller name.

您可以编写从 Route 类 GetRouteData 派生的自定义路由以去除破折号,但是当您调用 API 以生成 URL 时,您必须记住包含操作名称和控制器名称的破折号。

That shouldn't be too hard.

那应该不会太难。

回答by Nexxas

You can define a specific route such as:

您可以定义特定的路由,例如:

routes.MapRoute(
    "TandC", // Route controllerName
    "CommonPath/{controller}/Terms-and-Conditions", // URL with parameters
    new {
        controller = "Home",
        action = "Terms_and_Conditions"
    } // Parameter defaults
);

But this route has to be registered BEFOREyour default route.

但是这条路线必须你的默认路线之前注册。

回答by Cory Mawhorter

If you have access to the IIS URL Rewrite module ( http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx), you can simply rewrite the URLs.

如果您有权访问 IIS URL 重写模块 ( http://blogs.iis.net/ruslany/archive/2009/04/08/10-url-rewriting-tips-and-tricks.aspx),您可以简单地重写网址。

Requests to /my-controller/my-action can be rewritten to /mycontroller/myaction and then there is no need to write custom handlers or anything else. Visitors get pretty urls and you get ones MVC can understand.

对 /my-controller/my-action 的请求可以重写为 /mycontroller/myaction ,然后就不需要编写自定义处理程序或其他任何东西。访问者得到漂亮的 url,你得到 MVC 可以理解的。

Here's an example for one controller and action, but you could modify this to be a more generic solution:

这是一个控制器和操作的示例,但您可以将其修改为更通用的解决方案:

<rewrite>
  <rules>
    <rule name="Dashes, damnit">
      <match url="^my-controller(.*)" />
      <action type="Rewrite" url="MyController/Index{R:1}" />
    </rule>
  </rules>
</rewrite>

The possible downside to this is you'll have to switch your project to use IIS Express or IIS for rewrites to work during development.

可能的缺点是您必须将项目切换为使用 IIS Express 或 IIS 进行重写,以便在开发过程中工作。

回答by gregtheross

I'm still pretty new to MVC, so take it with a grain of salt. It's not an elegant, catch-all solution but did the trick for me in MVC4:

我对 MVC 还是很陌生,所以请持保留态度。这不是一个优雅的、包罗万象的解决方案,但在 MVC4 中为我做了诀窍:

routes.MapRoute(
    name: "ControllerName",
    url: "Controller-Name/{action}/{id}",
    defaults: new { controller = "ControllerName", action = "Index", id = UrlParameter.Optional }
);