31
考慮到重定向如何配置HttpClient在收到301 HTTP狀態碼時不自動重定向?
public class ThisController : ApiController
{
/* more methods */
public override HttpResponseMessage Post()
{
var result = new HttpResponseMessage(HttpStatusCode.MovedPermanently);
// Post requests should be made to "ThatController" instead.
string uri = Url.Route("That", null);
result.Headers.Location = new Uri(uri, UriKind.Relative);
return result;
}
}
試圖驗證POST'ing數據「API/this」將重定向的ASP.NET Web API服務你「API /那」,我有以下的測試方法:
[TestMethod]
public void PostRedirects()
{
using (var client = CreateHttpClient("application/json"))
{
var content = CreateContent(expected, "application/json");
using (var responseMessage = client.PostAsync("api/this", content).Result)
{
Assert.AreEqual(HttpStatusCode.MovedPermanently, responseMessage.StatusCode);
Assert.AreEqual(new Uri("https://api.example.com/api/that"), responseMessage.Headers.Location);
}
}
}
protected HttpClient CreateHttpClient(string mediaType)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://api.example.com/");
MediaTypeWithQualityHeaderValue headerValue = MediaTypeWithQualityHeaderValue.Parse(mediaType);
client.DefaultRequestHeaders.Accept.Add(headerValue);
client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("deflate"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(new ProductHeaderValue("MyProduct", "1.0")));
client.MaxResponseContentBufferSize = 1024*1024*8;
return client;
}
protected ObjectContent CreateContent(T model, string mediaType)
{
var requestMessage = new HttpRequestMessage();
MediaTypeFormatter mediaTypeFormatter = null;
switch (mediaType)
{
case "application/json":
mediaTypeFormatter = new JsonMediaTypeFormatter();
break;
case "application/xml":
case "text/xml":
mediaTypeFormatter = new XmlMediaTypeFormatter();
break;
default:
Assert.Fail();
break;
}
return requestMessage.CreateContent(
model,
new[] { mediaTypeFormatter },
new FormatterSelector());
}
真正發生的是一個HTTP狀態代碼發送到客戶端的正確位置標頭和HttpClient的然後自動執行對URI一個GET。結果,我的測試永遠不會通過。
如何配置HttpClient在收到301時不自動重定向,以便我可以驗證我的服務器響應?
的可能的複製[?我怎樣才能得到System.Net.Http.HttpClient不遵循302個重定向(http://stackoverflow.com/questions/10453892/how-can -i-得到系統淨HTTP-HttpClient的對不遵循-302重定向) –