【问题标题】:c# 307 automatic temporary redirect problemc# 307 自动临时重定向问题
【发布时间】:2019-07-29 05:58:59
【问题描述】:

我需要将客户端请求从一台服务器临时自动重定向到另一台服务器。 从服务器端:

string url = Constants.UrlRedirect;
Response.Headers.Add("Location", url);
return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status307TemporaryRedirect);

但是,从客户端来看,不会发生自动重定向,进程陷入异常(状态码 307)。我可以通过 WebException 提供重定向,但我不想这样做。如何设置自动重定向?请帮忙。 客户端代码:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/json";

using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
   string json = JsonConvert.SerializeObject(post);
   streamWriter.Write(json);
   streamWriter.Flush();                                                                                                                             
   streamWriter.Close();
}

HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
string result = string.Empty;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
   result = streamReader.ReadToEnd();
}

【问题讨论】:

  • 几个疑问。你的客户是什么?它是一个 API 吗?因为客户端代码也在 C# 中。其次,如果是API,你想要什么样的重定向?
  • 是的。客户端是 c# 中的桌面应用程序,服务器是 c# 中的 API。我想将请求重定向到另一个 API 服务器。不改变方法(“Post”应该是“Post”)。
  • 您可以在桌面应用程序中拥有一个基本 url。只需相应地更新它的值。
  • 可以随时进行临时重定向。它可能不会发生。如果客户端收到 307 作为响应,它必须将请求重定向到另一个服务器。否则,它接收并处理来自第一台服务器的响应。这应该是自动的。
  • 我尝试通过更改基本 URL 进行重定向,但它需要异常处理并再次发送请求。有用。但是,我正在寻找一种方法来毫无例外地做到这一点,但使用标题。自动重定向。

标签: c# .net redirect http-status-code-307


【解决方案1】:

在我的情况下,我得到相同的状态代码 307。解决方案是这个答案的组合:https://stackoverflow.com/a/46257876/9674093 和来自 WebException 的正确重定向链接。 正确的链接在“Location”下的 e.Response 的 WebHeaderCollection 中。

要得到它,你可以使用它(在我的例子中它是一个值 4):

Uri Link = new Uri(e.Response.Headers.Get(4));

或类似的东西:

Uri Link = new Uri(e.Response.Headers.Get("Location"));

例子:

WebResponse response;
        try {
           response = GetWebResponse(your_url);
        }
        catch(WebException e)) {
           if(e.Message.Contains("307")
             {
             //Get redirect-link from e.Response.Header.Location
             Uri Link = new Uri(e.Response.Headers.Get(4));
             // Start second request
             var second_request = GetWebRequest(Link);
             response = GetWebResponse(second_request);
             }
        }
                    

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2023-03-29
    • 2020-09-06
    • 2017-05-22
    • 2018-03-13
    • 2010-12-11
    • 2022-07-06
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多