【问题标题】:Change Controller Route in ASP.NET Core在 ASP.NET Core 中更改控制器路由
【发布时间】:2018-01-30 01:37:02
【问题描述】:

所以我有一个HomeController,要与Actions 一起访问它,我必须输入url.com/home/action

是否可以将其更改为 url.com/anothernamethatpointstohomeactually/action 之类的其他名称?

【问题讨论】:

    标签: c# asp.net-core routing asp.net-core-mvc


    【解决方案1】:

    我建议你使用属性路由,当然这取决于你的场景。

    [Route("prefix")]
    public class Home : Controller {
    
        [HttpGet("name")]
        public IActionResult Index() {
        }
    
    }
    

    这将在url.com/prefix/name 找到

    属性路由有很多选项,一些示例:

    [Route("[controller]")] // there are placeholders for common patterns 
                               as [area], [controller], [action], etc.
    
    [HttpGet("")] // empty is valid. url.com/prefix
    
    [Route("")] // empty is valid. url.com/
    
    [HttpGet("/otherprefix/name")] // starting with / won't use the route prefix
    
    [HttpGet("name/{id}")]
    public IActionResult Index(int id){ ... // id will bind from route param.
    
    [HttpGet("{id:int:required}")] // you can add some simple matching rules too.
    

    查看Attribute Routing official docs

    【讨论】:

      【解决方案2】:

      使用控制器顶部的 Route 属性将允许您在整个控制器上定义路由。 [Route("anothernamethatpointstohomeactually")]

      您可以阅读更多here

      【讨论】:

        【解决方案3】:

        您可以在 Startup.Configure 块内的 Startup.Configure 方法中添加新的 Routes

        routes.MapRoute(
            name: "SomeDescriptiveName",                      
            template: "AnotherNameThatPointsToHome/{action=Index}/{id?}",
            defaults: new { controller = "Home"} 
        );
        

        代码与 ASP.NET MVC 非常相似。

        有关详细信息,请参阅Routing in ASP.NET Core

        下面是 ASP.NET MVC(不是 ASP.NET Core MVC)

        您还可以通过routes.MapRoute 在您的RouteConfig 中添加新的Route

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

        确保在定义 Default 路由之前插入代码。

        欲了解更多信息,请访问docs

        【讨论】:

        • 在 .net 核心 3.1 中。你需要使用 app.useEndPoints();
        【解决方案4】:

        您可以通过修改路由配置来更改您的网址。 它有点像 htaccess,但不是真的。 https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/creating-custom-routes-cs

        另一种解决方案是创建一个页面并进行服务器重定向。

        Server.Transfer
        

        【讨论】:

        • Server.Transfer 在 asp.net core mvc 中不存在。
        • 您的链接似乎已损坏。
        猜你喜欢
        • 2019-05-27
        • 2016-10-22
        • 1970-01-01
        • 2017-01-08
        • 1970-01-01
        • 2020-04-18
        • 1970-01-01
        • 1970-01-01
        • 2019-08-23
        相关资源
        最近更新 更多