为什么我们需要更多代码才能在 .net 核心中从 www 重定向到非 www? [英] Why we need more codes to redirecting from www to non-www in .net core?

查看:14
本文介绍了为什么我们需要更多代码才能在 .net 核心中从 www 重定向到非 www?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法将 www 重定向到非 www 并找到一些帖子和代码,例如 这个:

I was looking to find a way to redirect www to non-www and find some posts and codes like this:

public class NonWwwRule : IRule
{
   public void ApplyRule(RewriteContext context)
    {
      var req = context.HttpContext.Request;
      var currentHost = req.Host;
      if (currentHost.Host.StartsWith("www."))
         {
             var newHost = new HostString(currentHost.Host.Substring(4), currentHost.Port ?? 80);
             var newUrl = men 
              StringBuilder().Append("https://").Append(newHost).Append(req.PathBase)
             .Append(req.Path).Append(req.QueryString);
              context.HttpContext.Response.Redirect(newUrl.ToString(), true);
              context.Result = RuleResult.EndResponse;
            }
     }
}

并像这样使用这个类:

var options = new RewriteOptions();
options.Rules.Add(new NonWwwRule());
app.UseRewriter(options);

经过测试,它工作正常,但从非 www 重定向到 www 只需要一行代码:

Tested and it works fine but to redirect from non-www to www just need a line of code:

app.UseRewriter(new RewriteOptions().AddRedirectToWww());

我的问题是为什么从 www 重定向到非 www 需要很多代码?

My question is that why redirecting from www to non-www needs a lot of code?

在 .net core 3.1 中没有访问 web.config 和 IIS 的情况下,是否有更好的方法来处理它,而无需大量代码?

Is there a better way without a lot of code to handle it without accessing to web.config and IIS in .net core 3.1?

推荐答案

微软好像在ASP.NET Core 5.0中添加了扩展方法

It seems Microsoft add the extension method in ASP.NET Core 5.0

https://docs.microsoft.com/it-it/dotnet/api/microsoft.aspnetcore.rewrite.rewriteoptionsextensions.addredirecttowww?view=aspnetcore-5.0

在 3.1 版本中,我们需要像您一样添加一个类

In version 3.1 we need to add a class like you do

附言您的代码中存在拼写错误.

P.S. There is a typo in your code.

var newUrl = men StringBuilder()

这篇关于为什么我们需要更多代码才能在 .net 核心中从 www 重定向到非 www?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆