簡體   English   中英

c#307自動臨時重定向問題

[英]c# 307 automatic temporary redirect problem

我需要設置客戶端請求從一台服務器到另一台服務器的臨時自動重定向。 從服務器端:

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

在我的情況下,我得到相同的狀態代碼 307。解決方案是以下答案的組合: https ://stackoverflow.com/a/46257876/9674093 和來自 WebException 的正確重定向鏈接。 正確的鏈接位於“位置”下 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);
             }
        }
                    

暫無
暫無

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

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