目前我面临一个问题,当尝试从 MVC Api Client 调用 Web Api put 方法时,让我们在下面描述我的代码结构
测试模型(Web Api端)
public sealed class Test
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
Web Api PUT 方法
public HttpResponseMessage Put(string token, IEnumerable<Test> data)
{
[...]
return Request.CreateResponse(HttpStatusCode.OK);
}
Web Api 自定义过滤器
public sealed class ValidateFilterAttribute : ActionFilterAttribute
{
/// <summary>
///
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
从 Web Api 客户端调用
async System.Threading.Tasks.Task VerifiedFAccount()
{
using (var client = GetHttpClient())
{
var url = string.Concat("/api/Verfication", "?token=", token);
var data = new SampleTest { Id = 1, Name = "xxx" };
var temp = new List<SampleTest>();
temp.Add(data);
using (HttpResponseMessage response = await client.PutAsJsonAsync
<IEnumerable<SampleTest>>(url, temp).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
}
}
}
客户端代码无法执行 Api 调用(即使我将调试点放在 Web Api Put 方法中,也无法命中调试点)并且总是收到以下错误响应
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
X-SourceFiles: =?UTF-8?B?STpcRGV2QXJlYUxvY2FsXENPTVBBTlkgLSBQU1AgUFJPSkVDVFNcRS1BdXRob3JpdHkgLSBBdXN0cmVsaXlhXFNvdXJjZUNvbnRyb2xcVHJ1bmtcMDYgRGVjIDIwMTNcRS1BdXRob3JpdHkuQXBpIC0gMjAxM1xFYXV0aG9yaXR5LldlYi5BcGkuUHJlc2VudGF0aW9uTGF5ZXJcYXBpXFNtc2ZBY2NvdW50VmVyZmljYXRpb24=?=
Cache-Control: no-cache
Date: Mon, 14 Apr 2014 11:23:27 GMT
Server: Microsoft-IIS/8.0
Content-Length: 2179
Content-Type: application/json; charset=utf-8
Expires: -1
}}
但是当我从测试模型(Web Api 端)中删除[Required]
时。然后上述客户端代码执行成功。
请告诉我这种令人困惑的行为的原因是什么?
最佳答案
您面临的问题可能是由于数据验证时默认配置的行为造成的。你有一个Required
归因于不可空类型,并且自 int
不能为 null,如果传入请求未提供该值,它将始终有一个值(默认为 0
)。
在这些情况下,模型验证器将抛出异常,因为 Required
没有意义。属性上的属性不能为空。
更改 MVC 应用程序设置的简单方法:
DataAnnotationsModelValidatorProvider
.AddImplicitRequiredAttributeForValueTypes = false;
这将消除框架引发的错误。这引入了一个问题,您将得到值 0
即使请求不包括该属性(property)。让你的整数为 Nullable<int>
更有意义。 Required
属性将能够处理 null
值,您将知道传入的请求是否包含该属性
public sealed class Test
{
[Required]
public int? Id { get; set; }
[Required]
public string Name { get; set; }
}
关于api - 如何在 Web Api Put 中使用 [Required] 属性和模型状态验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23062936/