gpt4 book ai didi

c# - 如何在ASP.NET Core中处理路由请求 "john.myexample.com"

转载 作者:行者123 更新时间:2023-12-03 02:49:28 25 4
gpt4 key购买 nike

假设我的应用程序 URL 是 myexample.com,myexample.com 有用户 john,他有一个公共(public)个人资料链接 john.myexample.com如何在 ASP.NET Core 应用程序中处理此类请求并映射到具有操作 ProfileUserController,将 username 作为参数,并且 返回约翰个人资料。

routes.MapRoute(
name: "user_profile",
template: "{controller=User}/{action=Profile}/{username}");

最佳答案

内置ASP.NET Core Routing不提供任何请求子域的模板。这就是为什么您需要实现自定义路由器来覆盖这种情况。

实现将非常简单。您应该解析传入请求的主机名以检查它是否是配置文件子域。如果是这样,则在路由数据中填写 Controller 、操作和用户名。

这是一个工作示例:

路由器实现:

public class SubdomainRouter : IRouter
{
private readonly Regex hostRegex = new Regex(@"^(.+?)\.(.+)$", RegexOptions.Compiled);

private readonly IRouter defaultRouter;
private readonly string domain;
private readonly string controllerName;
private readonly string actionName;

public SubdomainRouter(IRouter defaultRouter, string domain, string controllerName, string actionName)
{
this.defaultRouter = defaultRouter;
this.domain = domain;
this.controllerName = controllerName;
this.actionName = actionName;
}

public async Task RouteAsync(RouteContext context)
{
var request = context.HttpContext.Request;
var hostname = request.Host.Host;

var match = hostRegex.Match(hostname);
if (match.Success && String.Equals(match.Groups[2].Value, domain, StringComparison.OrdinalIgnoreCase))
{
var routeData = new RouteData();
routeData.Values["controller"] = controllerName;
routeData.Values["action"] = actionName;
routeData.Values["username"] = match.Groups[1].Value;

context.RouteData = routeData;
await defaultRouter.RouteAsync(context);
}
}

public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return defaultRouter.GetVirtualPath(context);
}
}

在Startup.Configure()中注册:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc(routes =>
{
routes.Routes.Add(new SubdomainRouter(routes.DefaultHandler, "myexample.com", "User", "Profile"));

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

示例 Controller :

public class UserController : Controller
{
[HttpGet]
public IActionResult Profile(string username)
{
return Ok();
}
}

Sample Project on GitHub

更新(在开发环境中使用本地主机的路由)

在开发环境中为本地主机使用此类路由有两种选择:

  1. 第一个完全模拟生产环境中的子域 URL。要使其正常工作,您应该配置您的主机文件,以便 john.myexample.com 指向 127.0.0.1 并使您的 ASP.NET Core 应用程序接受此类主机的请求。在这种情况下,您不需要在路由中进行任何额外的调整,因为请求将具有与生产中相同的 URL(仅添加端口):http://john.myexample.com:12345/

  2. 如果您想让事情变得简单并使用指向 localhost 的常用开发 URL,您应该绕过所描述的 SubdomainRouter (因为它解析子域,这不适用于 localhost) 并使用常用的 ASP.NET Core 路由。以下是本例调整后的路由配置:

    app.UseMvc(routes =>
    {
    if (env.IsDevelopment())
    {
    routes.MapRoute(
    name: "user-profile",
    template: "profiles/{username}",
    defaults: new { controller = "User", action = "Profile" });
    }
    else
    {
    routes.Routes.Add(new SubdomainRouter(routes.DefaultHandler, "myexample.com", "User", "Profile"));
    }

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

    现在,如果您向 http://localhost:12345/profiles/john 这样的 URL 发送请求,则将使用正确的用户名调用 UserController.Profile 操作。

关于c# - 如何在ASP.NET Core中处理路由请求 "john.myexample.com",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49450491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com