我有一个APS.NET Core 2.0 API,我正在编写测试客户端。测试客户端是控制台应用程序。我希望能够读取和显示可能处于模型状态的may API调用返回的任何错误。
在我的API中,如果模型无效,我会返回模型以及状态422,如下所示;
if (!ModelState.IsValid)
{
return new UnprocessableEntityObjectResult(ModelState);
}
UnprocessableEntityObjectResult只是一个帮助类,如下所示;
public class UnprocessableEntityObjectResult : ObjectResult
{
public UnprocessableEntityObjectResult(ModelStateDictionary modelState)
: base(new SerializableError(modelState))
{
if (modelState == null)
{
throw new ArgumentNullException(nameof(modelState));
}
StatusCode = 422;
}
}
我的意图是在出错时将模型状态返回给客户端。
我的测试客户端是一个控制台应用程序,我正在寻找一种方法来检查模型状态并列出任何错误。
在我的控制台应用程序中,我有以下从Main调用的方法;
static async Task CreateUploadRecordAsync()
{
httpClient.BaseAddress = new Uri("https://localhost:44369");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string relativeUrl = "/api/upload";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, relativeUrl);
HttpResponseMessage response = new HttpResponseMessage();
using (var content = new MultipartFormDataContent())
{
//Add content values here...
request.Content = content;
response = await httpClient.SendAsync(request);
}
if (response.IsSuccessStatusCode)
{
string result = response.Headers.Location.ToString();
Console.WriteLine("Success:\n");
Console.WriteLine($"New Record Link: [{result}]\n");
}
else
{
//Add code here to get model state from response
Console.WriteLine($"Failed to create new upload record. Error: {response.ReasonPhrase}\n");
}
}
我正在寻找一个示例,说明如何提取“/在此处添加代码以从响应中获取模型状态”注释之后存在的模型状态。
有什么想法吗?