使用Asp.Net Core中间件将非WWW重定向到WWW

编程入门 行业动态 更新时间:2024-10-24 06:25:39
本文介绍了使用Asp.Net Core中间件将非WWW重定向到WWW的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在ASP.Net Core应用程序启动时,我有:

On an ASP.Net Core application startup I have:

RewriteOptions rewriteOptions = new RewriteOptions(); rewriteOptions.AddRedirectToHttps(); applicationBuilder.UseRewriter(rewriteOptions);

在生产中,我需要将所有非WWW重定向到WWW Urls

When in Production I need to redirect all Non WWW to WWW Urls

例如:

domain/about > www.domain/about

如何使用重写中间件来做到这一点?

How can I do this using Rewrite Middleware?

我认为可以使用AddRedirect和Regex完成此操作

I think this can be done using AddRedirect and Regex:

Github-ASP.NET Core重定向文档

但不确定如何做...

But not sure how to do it ...

推荐答案

可重用的替代方法是创建自定义重写规则和相应的扩展方法,以将该规则添加到重写选项中.这与AddRedirectToHttps的工作原理非常相似.

A reusable alternative would be to create a custom rewrite rule and a corresponsing extension method to add the rule to the rewrite options. This would be very similar to how AddRedirectToHttps works.

自定义规则:

public class RedirectToWwwRule : IRule { public virtual void ApplyRule(RewriteContext context) { var req = context.HttpContext.Request; if (req.Host.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase)) { context.Result = RuleResult.ContinueRules; return; } if (req.Host.Value.StartsWith("www.", StringComparison.OrdinalIgnoreCase)) { context.Result = RuleResult.ContinueRules; return; } var wwwHost = new HostString($"www.{req.Host.Value}"); var newUrl = UriHelper.BuildAbsolute(req.Scheme, wwwHost, req.PathBase, req.Path, req.QueryString); var response = context.HttpContext.Response; response.StatusCode = 301; response.Headers[HeaderNames.Location] = newUrl; context.Result = RuleResult.EndResponse; } }

扩展方法:

public static class RewriteOptionsExtensions { public static RewriteOptions AddRedirectToWww(this RewriteOptions options) { options.Rules.Add(new RedirectToWwwRule()); return options; } }

用法:

var options = new RewriteOptions(); options.AddRedirectToWww(); options.AddRedirectToHttps(); app.UseRewriter(options);

将来的重写中间件版本将包含规则和相应的扩展方法.参见此提取请求

Future versions of the rewrite middleware will contain the rule and the corresponding extension method. See this pull request

更多推荐

使用Asp.Net Core中间件将非WWW重定向到WWW

本文发布于:2023-11-05 09:53:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560525.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   重定向   Net   Asp   WWW

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!