【发布时间】:2019-11-18 09:28:27
【问题描述】:
我有一个带有 web.api 的 asp.net 网站(“/v”),它基于请求中的 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()
{
}
}
}
【问题讨论】:
-
您无法重定向 POST。您可以返回一个将数据发布到其他网站的插页式页面,或者您的网站可以充当代理并直接发布。
-
为了解决我的问题,我决定用 NGINX 创建一个反向代理,谢谢
标签: c# asp.net asp.net-mvc-4 asp.net-web-api