58

考虑一个重定向的 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;
    }
}

尝试验证将数据发布到“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 时不自动重定向,以便我可以验证我的服务器响应?

4

1 回答 1

117

尝试:

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

HttpClient client = new HttpClient(handler);
于 2012-05-18T05:38:59.220 回答