【问题标题】:Custom Routing URL in MVC (appurl/{uniqueId}/{controller}/{action}/{id})MVC 中的自定义路由 URL (appurl/{uniqueId}/{controller}/{action}/{id})
【发布时间】:2018-12-25 10:08:21
【问题描述】:

我们正在尝试用 c# 构建一个 mvc 应用程序。我们希望更改路由配置,使其在域 url 和控制器名称之间具有 uniqueId。uniqueId 是动态的,并且基于 uniqueId,应用程序将通过弹性数据库服务器连接到相应的数据库。

问题在于 mvc 将 uniqueId 视为控制器。当我搜索时,我发现了一些解决方案,其中 uniqueId 是静态的并且已经定义。请找到错误图像的链接link

例如: 我想构建如下所示的东西,但它不起作用

网址:portal.example.com/{uniqueId}/Account/login

RouteConfig

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

请帮助我们采用这种方法。有没有其他方法可以让这个工作。提前致谢

编辑:很抱歉在默认值中使用主机名而不是 uniqueId。我已编辑为 uniqueid

【问题讨论】:

  • 它应该可以正常工作。是否定义了其他routes
  • 嗨,Karan,只有这是应用程序中配置的路由
  • 您使用的是 web-api 还是 web-application?您提到了两个不同的网址,一个在标题中为api/{uniqueId}/{controller}/{action}/{id},另一个在描述中为portal.example.com/{uniqueId}/Account/login,哪个实际在使用?
  • 嗨,Karan,很抱歉出现拼写错误。它是appurl(Web应用程序)。
  • 我已经尝试过,它对我有用。只需从 defaults 中删除 hostname,因为它没有被使用。

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

写在RouteConfig.cs

routes.MapMvcAttributeRoutes();

之后,将这个顶部写在你的控制器上。

[Route("your_controller/your_ındex")]

【讨论】:

  • 您好艾伦,感谢您的回复。我正在寻找像 Azure devops application url 这样的解决方案。如果您查看 Azure devops,它的多租户应用程序服务于多个客户。 例如:dev.azure.com/{clientname} - 客户端名称可以是任何名称,它将充当弹性数据库池的租户 ID。我尝试实现这个解决方案,但是 MVC 框架不支持这种模式并且它考虑 {clientname} 作为控制器名称。请让我知道是否有任何解决方案。
【解决方案2】:

路由表中生成的 URL 是在应用程序启动时生成的。它们将始终保持静止。

一种解决方法是:-

[NonAction]
public static string GetGuid()
{
    string myUniqueID = Guid.NewGuid().ToString(); //My Unique ID Logic


    return myUniqueID;
}

您可以在整个应用程序中调用它。

【讨论】:

    【解决方案3】:

    我通过将“uniqueid”添加到默认值来尝试您的代码,它对我来说很好

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

    【讨论】:

    • 嗨欣喜若狂,我收到以下错误。请找到图片链接link
    • 你确定吗,你在默认对象中添加了 'uniqueId = UrlParameter.Optional'。
    • 嗨欣喜若狂,很抱歉在问题描述的默认值中使用主机名而不是 uniqueId。我用 uniqueId 编辑是欣喜若狂,我在默认值中添加了 uniqueId
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 2020-07-13
    • 1970-01-01
    相关资源
    最近更新 更多