gpt4 book ai didi

asp.net-core-2.0 - 自定义网址重写

转载 作者:行者123 更新时间:2023-12-01 01:46:12 26 4
gpt4 key购买 nike

我想使用UseRewriter中间件重写一个简单的URL。

var rewrite = new RewriteOptions()
.AddRedirect("Page1From", "Page1To") // Redirect
.AddRewrite("Page2From", "Page2To", true); // Rewrite

app.UseRewriter(rewrite);

结果是,URL“/Page1From”将被重定向到“Page1To”,URL“Page2From”将显示“/Page2To”的内容而无需重定向。

我想通过使用数据库中的数据来实现AddRewrite方法,但是我只找到了如何使用自定义规则进行重定向。
var rewrite = new RewriteOptions()
.AddRedirect("Page1From", "Page1To") // Redirect
.AddRewrite("Page2From", "Page2To", true); // Rewrite
.Add(new MoviesRedirectRule( // Custom Rule
matchPaths: new[] { "/Page3From1", "/Page3From2", "/Page3From3" },
newPath: "/Page3To"));

app.UseRewriter(rewrite);

规则如下:
public class MoviesRedirectRule : IRule
{
private readonly string[] matchPaths;
private readonly PathString newPath;

public MoviesRedirectRule(string[] matchPaths, string newPath)
{
this.matchPaths = matchPaths;
this.newPath = new PathString(newPath);
}

public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;

// if already redirected, skip
if (request.Path.StartsWithSegments(new PathString(this.newPath)))
{
return;
}

if (this.matchPaths.Contains(request.Path.Value))
{
var newLocation = $"{this.newPath}{request.QueryString}";

var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status302Found;
context.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] = newLocation;
}
}
}

这将重定向以下URL:
  • /Page3From1
  • /Page3From2
  • /Page3From3

  • 到/Page3To

    我想创建类似的内容,但不会重定向,但我想重写该URL,以便该URL保持不变,但将显示指定URL的内容。

    有人可以告诉我为了使响应对象起作用我必须进行哪些更改?

    最佳答案

    调用RewriteRule时添加的AddRewrite()只是替换了请求中的URI部分(link to source code):

    request.Scheme = scheme;
    request.Host = host;
    request.Path = pathString;
    request.QueryString = query.Add(request.QueryString);

    在您的情况下,由于仅替换 Path部分,因此 ApplyRule方法将非常简单:
    public void ApplyRule(RewriteContext context)
    {
    var request = context.HttpContext.Request;

    if (matchPaths.Contains(request.Path.Value))
    {
    request.Path = newPath;
    context.Result = RuleResult.SkipRemainingRules;
    }
    }

    关于asp.net-core-2.0 - 自定义网址重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49131720/

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