簡體   English   中英

在自定義HttpModule中使用POST方法進行Response.Redirect

[英]Response.Redirect with POST method in custom HttpModule

我有一個帶有web.api的asp.net網站(“ / v”),該web.api必須基於請求中的cookie重定向到另一個站點(“ / v2”)。

因此,如果有cookie,則請求必須重定向到“ / v2 / api ...”,如果沒有cookie,則請求必須繼續到“ / v / api / ...”

因此,我實現了自定義HttpModule以完成重定向請求的此任務,但是即使請求是POST方法,重定向也始終使用GET進行。

如何使用正確的方法重定向請求?

下面的示例代碼。

提前致謝

using System;
using System.Web;
using System.Linq;

namespace Sample
{
    public class VersionModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += OnContextBeginRequest;
        }

        private void OnContextBeginRequest(object sender, EventArgs e)
        {
            try
            {
                HttpApplication app = (HttpApplication)sender;

                if (app.Context.Request.Cookies.AllKeys.Contains("version"))
                {
                    string newUrl = @"https://sample.com/v";

                    var cookie = app.Context.Request.Cookies.Get("version");
                    if (!string.IsNullOrEmpty(cookie.Value))
                    {
                        if (cookie.Value == "2")
                        {
                            newUrl += "2";
                            string parameters = app.Context.Request.Url.PathAndQuery.Replace("v/", "");
                            newUrl = newUrl + parameters;

                            // this call alway a GET!! I need a POST method!
                            app.Context.Response.Redirect(newUrl, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        public void Dispose()
        {
        }

    }
}

在您的評論中,您聲明“為解決我的問題,我決定使用NGINX創建反向代理”。

作為替代方案,更內聯您的原始問題...

您可以使用HTTP 307臨時重定向 ,其中方法(在這種情況下為POST )和原始請求的正文將被重用於執行重定向的請求。

app.Context.Response.StatusCode = 307;
app.Context.Response.RedirectLocation = newUrl;
app.Context.Response.End();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM