简体   繁体   English

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

[英]How to use System.Net.Http.HttpClient to GET after POST with AllowAutoRedirect = true

Here is the code to create a client and POST an object. 以下是创建客户端和POST对象的代码。 It is my understanding that setting AllowAutoRedirect = true would enable the ability for the client to follow the redirect then do a GET and I would be able to deserialize said object. 我的理解是,设置AllowAutoRedirect = true将使客户端能够遵循重定向然后执行GET,并且我能够反序列化所述对象。 My testing has proven unsuccessful so far. 到目前为止,我的测试证明是不成功的。 Is there something that I may have overlooked? 有什么我可能会忽略的吗?

Web API endpoint: 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);
    }
}

Client code: 客户代码:

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 logs. Wireshark日志。

POST /v1/Contacts HTTP/1.1 (application/json) HTTP/1.1 201 Created Location: http://api01.example.com/v1/Contacts/10135052 POST / v1 / Contacts HTTP / 1.1(application / json)HTTP / 1.1 201创建位置: http//api01.example.com/v1/Contacts/10135052

and that's it, no GET ( http://api01.example.com/v1/Contacts/10135052 ) after as far as I can tell. 就这一点而言,据我所知,没有GET( http://api01.example.com/v1/Contacts/10135052 )。

From the log trace you added, it looks like the response from the POST is a 201 (Created); 从您添加的日志跟踪中,看起来POST的响应是201(已创建); there is no redirect. 没有重定向。 The response does contain a URL (either in a header or the body, hard to tell) but it will not mean anything special. 响应确实包含一个URL(在标题或正文中,很难说)但它并不意味着什么特别的。 Your client will need to parse the URL itself and issue the subsequent GET request explicitly. 您的客户端需要解析URL本身并明确发出后续GET请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM