Microsoft has a nuget package named Rewrite, A middleware where you can rewrite or redirect some requests, but also there is a way to write a custom Rule, where you can capture the subdomain and add it to the request path:public class RewriteSubdomainRule : IRule { public void ApplyRule(RewriteContext context) { var request = context.HttpContext.Request; var host = request.Host.Host; // Check if the host is subdomain.domain.com or subdomain.localhost for debugging if (Regex.IsMatch(host, @"^[A-Za-z\d]+\.(?:[A-Za-z\d]+\.[A-Za-z\d]+|localhost)$")) { string subdomain = host.Split('.')[0]; //modifying the request path to let the routing catch the subdomain context.HttpContext.Request.Path = "/subdomain/" + subdomain + context.HttpContext.Request.Path; context.Result = RuleResult.ContinueRules; return; } context.Result = RuleResult.ContinueRules; return; } }在Startup.cs上On Startup.cs您必须添加中间件才能使用自定义重写规则:You have to add the middleware to use the custom rewrite rule: app.UseRewriter(new RewriteOptions().Add(new RewriteSubdomainRule())); 在这行之后,我定义了一条路由,该路由接收添加在请求路径上的子域并将其分配给子域变量:And after this lines I define a route that receives the subdomain added on the request path and assign it to the subdomain variable: app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "subdomain", template: "subdomain/{subdomain}/{controller=Home}/{action=Index}/{id?}"); });在控制器上,您可以像这样使用它On the controller you can use it like thispublic async Task<IActionResult> Index(int? id, string subdomain){} 这篇关于区域和子域路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-17 04:43