gpt4 book ai didi

asp.net - 如何使用 HttpContext 重定向

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

我的问题是:

  • 所以我需要创建一个自定义类/HttpHandler 并将这段代码扔进去?或者我可以把它放在像 global.asax 这样的其他地方吗?
  • 我如何检查传入的主机(因此检查 www.mydomain.com)以便我知道何时重定向?

  • 代码:
    if ("comes from certain domain")
    {
    context.Response.Status = "301 Moved Permanently";
    context.Response.AddHeader("Location", "http://www.testdomain.com/Some.aspx");
    }

    最佳答案

    将其粘贴到 App_Code 文件夹中的新 .cs 文件中:

    using System;
    using System.Web;

    public class TestModule : IHttpModule
    {
    public void Init(HttpApplication context) {
    context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e) {
    HttpApplication app = (HttpApplication)sender;
    if (app.Request.Url.Host == "example.com") {
    app.Response.Status = "301 Moved Permanently";
    app.Response.AddHeader("Location", "http://www.testdomain.com/Some.aspx");
    }
    }

    public void Dispose() {
    }
    }

    然后将其添加到 system.web 中的 web.config 中:
    <httpModules>
    <add type="TestModule" name="TestModule" />
    </httpModules>

    关于asp.net - 如何使用 HttpContext 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1822060/

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