简体   繁体   中英

Response.Redirect with POST method in custom HttpModule

i have asp.net web site ("/v") with web.api that based on cookie in the request must be redirect to another site ("/v2").

So if there is the cookie the request must be redirect to "/v2/api...", it there isn't the cookie the request must be continue to "/v/api/..."

So i've implemented a custom HttpModule to accomplish this task that redirect the request, but the redirect is always with GET even if the request is a POST method.

How can i redirect the request with correct method?

Below sample code.

Thanks in advance

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()
        {
        }

    }
}

In your comment you state "to resolve my problems i've decided to create a reverse proxy with NGINX".

As an alternative more inline with your original question...

You could use a HTTP 307 Temporary Redirect where the method ( POST in this case) and the body of the original request are reused to perform the redirected request.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM