首页 文章

如何配置HttpClient在收到301 HTTP状态代码时不自动重定向?

提问于
浏览
41

考虑重定向的ASP.NET Web API服务

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数据到“api / this”会将你重定向到“api / that”,我有以下测试方法:

[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状态代码使用正确的Location头发送到客户端,然后HttpClient会自动对该URI执行GET . 结果,我的测试永远不会过去 .

如何配置HttpClient在收到301时不自动重定向,以便我可以验证我的服务器响应?

1 回答

  • 87

    尝试:

    var handler = new HttpClientHandler() 
    {
        AllowAutoRedirect = false
    };
    
    HttpClient client = new HttpClient(handler);
    

相关问题