如何在POST后使用System.Net.Http.HttpClient来使用AllowAutoRedirect = true

时间:2013-09-04 19:33:48

标签: c# asp.net dotnet-httpclient

以下是创建客户端和POST对象的代码。我的理解是,设置AllowAutoRedirect = true将使客户端能够遵循重定向然后执行GET,并且我能够反序列化所述对象。到目前为止,我的测试证明是不成功的。有什么我可能会忽略的吗?

Web API端点:

public HttpResponseMessage Post([FromBody] Contact contact) {

    try {
        // Add user

        ...

        var msg = Request.CreateResponse(HttpStatusCode.Created);
        msg.Headers.Location = new Uri(Request.RequestUri + "/" + customer.Person.PersonID);
        return msg;
    } catch (ValidationException tve) {
        var apiError = new ApiResponseMessage { Message = "Invalid contact" };
        foreach (var message in FilterErrors(tve.Messages)) {
            if (message.Contains("required", StringComparison.OrdinalIgnoreCase)) {
                apiError.Errors.Add(new ApiErrorMessage {
                    Code = ErrorCode.RequiredPropertyNotProvided,
                    Message = message
                });
            } else {
                apiError.Errors.Add(new ApiErrorMessage {
                    Code = ErrorCode.PropertyNotValid,
                    Message = message
                });
            }
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest, apiError);
    }
}

客户代码:

public Contact Post(Contact contact)
{
    try
    {
        var handler = new HttpClientHandler { AllowAutoRedirect = true};
        using (var client = new HttpClient(handler))
        {
            client.BaseAddress = new Uri(APIServer);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Add("X-ApiKey", APIKey.ToString());

            var response = client.PostAsJsonAsync("v1/Contacts", contact).Result;
            if (response.IsSuccessStatusCode)
            {
                Log.DebugFormat("Post v1/Contacts => {0} ({1})", response.StatusCode, response.ReasonPhrase);

                var result = JsonConvert.DeserializeObject<Contact>(response.Content.ReadAsStringAsync().Result);
                // This object is null

            }
            else
            {
                Log.ErrorFormat("Post v1/Contacts => {0} ({1})", response.StatusCode, response.ReasonPhrase);    
                var result = JsonConvert.DeserializeObject<ApiMessageResponse>(
                        response.Content.ReadAsStringAsync().Result);                      
            }


        }

    }
    catch (Exception exception)
    {
        Log.Error(exception);
    }

    return null;
}

Wireshark日志。

POST / v1 / Contacts HTTP / 1.1(application / json) HTTP / 1.1 201已创建 地点:http://api01.example.com/v1/Contacts/10135052

就是这样,就我所知,没有GET(http://api01.example.com/v1/Contacts/10135052)。

1 个答案:

答案 0 :(得分:2)

从您添加的日志跟踪中,看起来POST的响应是201(已创建);没有重定向。响应确实包含一个URL(在标题或正文中,很难说)但它并不意味着什么特别的。您的客户端需要解析URL本身并明确发出后续GET请求。