这是创建客户端和 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 )。