【问题标题】:.NET Core razor page web app redirect to a new host name.NET Core razor 页面 Web 应用重定向到新主机名
【发布时间】:2019-05-06 18:56:17
【问题描述】:

我有一个默认页面设置为 /index.cshtml 的 .net 核心应用程序。 url www.xyz.com 重定向到 www.xyz.com/index(因为它是默认页面)。我想处理传入的请求并替换 url 中的主机名。 示例:- www.xyz.com/x --> 应该重定向到 www.abc.com/x。 我不想在 nginx 配置文件中执行此操作。我想在代码中做到这一点。

我有一个中间件来处理请求

public class GetMiddleware
{
    private RequestDelegate _next;


    public GetMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public Task Invoke(HttpContext context)
    {
        var request = context.Request;
        string path = request.Path.ToString();
       if(!string.IsNullOrEmpty(path))
        {
            //redirect to new url/path. I want to check if path exists/x or /whatever and redirect to new url/path

        }
        return _next.Invoke(context);
    }
}

}

【问题讨论】:

  • 您的问题是什么?请发布给您带来麻烦的代码。见How to Ask
  • @JohnWu 如果我的应用程序中不存在该资源,我想将传入的请求重定向到我的应用程序到不同的 url(在我的应用程序之外)。
  • 我知道这就是您想要的。你在哪一部分有问题?这里的大多数用户不会从头开始为您编写解决方案,但如果您已经完成了尝试,则会帮助您进行尝试。
  • @JohnWu 已添加请查看
  • 这是一个 MVC 应用程序吗?这个GetMiddleware 类究竟是如何从控制器调用的?正确的做法是从 action 方法中返回一个RedirectResult

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


【解决方案1】:

您必须编写响应(状态码 301 和 Location 标头)并返回:

public class GetMiddleware
{
    private RequestDelegate _next;

    public GetMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public Task Invoke(HttpContext context)
    {
        if (context.Request.Path == "/whatever")
        {
            context.Response.Headers.Add("Location", "https://example.com");
            context.Response.StatusCode = 302;
            return Task.CompletedTask;
        }

        return _next.Invoke(context);
    }
}

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 2020-07-09
    • 2021-05-16
    • 2019-03-11
    • 2022-01-21
    • 1970-01-01
    • 2021-09-09
    • 2018-01-31
    • 2019-02-18
    相关资源
    最近更新 更多