【问题标题】:How to render a razor page instead of static html content without redirecting如何在不重定向的情况下呈现剃须刀页面而不是静态 html 内容
【发布时间】:2020-03-19 20:30:43
【问题描述】:

在我使用的旧 ASP.NET WebForms 中

HttpApplication.Context.RewritePath

Global.asax 中重写 url 的方法 - 重定向而不实际更改浏览器中显示的 URL。

现在我在 ASP.NET Core 3.0 中使用以下代码将一些静态内容重定向到剃须刀页面:

public class RedirectHtmlRequests : IRule
{
    private readonly string _docPath;
    private readonly string _fldPublic;
    private readonly string _fldPrivate;

    public RedirectHtmlRequests(string docPath, string fldPublic, string fldPrivate)
    {
        this._docPath = docPath.ToLower();
        this._fldPublic = fldPublic.ToLower();
        this._fldPrivate = fldPrivate.ToLower();
    }

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

        if (request.Path.Value.EndsWith(".htm", StringComparison.OrdinalIgnoreCase)
            || request.Path.Value.EndsWith(".html", StringComparison.OrdinalIgnoreCase))
        {
            //response.StatusCode = StatusCodes.Status301MovedPermanently;
            //context.Result = RuleResult.EndResponse;
            int id = FindDocumentByUri(request.Path);
            if (id > 0)
            {
                //context.HttpContext.Response.Redirect(string.Format("/Dokument/{0}", id));
                var response = context.HttpContext.Response;
                response.StatusCode = StatusCodes.Status307TemporaryRedirect;
                context.Result = RuleResult.EndResponse;
                response.Headers[HeaderNames.Location] = (string.Format("/Dokument/{0}", id));
            }
        }
    }

Startup.cs

app.UseRewriter(new RewriteOptions().Add(new RedirectHtmlRequests("Dokumenty/", "Verejne/", "Duverne/")));
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetParent(env?.ContentRootPath).FullName, "Dokumenty")),
    RequestPath = "/Dokumenty"
});

但是行

response.Headers[HeaderNames.Location] = (string.Format("/Dokument/{0}", id));

实际上将浏览器窗口中的 url 重定向到/Dokument/{ID},这是不可取的。我应该改用什么命令?

【问题讨论】:

  • 术语方面的一点 - 重定向将根据定义影响浏览器中的 URL。 developer.mozilla.org/en-US/docs/Web/HTTP/Redirections 我怀疑你想要做的是为给定的 URL 呈现给定的页面(这更多的是 routing 问题)。
  • 是的,我想渲染该剃须刀页面而不是 html 内容。
  • 但在 WebForms 中它使用 HttpApplication.Context.RewritePath 工作。

标签: c# asp.net asp.net-core url-rewriting razor-pages


【解决方案1】:

HttpContext.Request.Path 替换为剃须刀页面的路径对我来说是诀窍:

if (id > 0)
{
    context.HttpContext.Request.Path = (string.Format("/Dokument/{0}", id));
    context.Result = RuleResult.SkipRemainingRules;
}

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2018-01-09
    • 2018-11-21
    • 2021-10-27
    相关资源
    最近更新 更多