使用的技术:Code First、ASP.NET Web API(restful 服务)和 HTML。
对于代码,我有一个名为 User 的域对象
public class User
{
[Required]
public Guid Id { get; set; }
[Required]
public string Email { get; set; }
[Required]
public byte[] PasswordHash { get; set; }
public bool IsDeleted { get; set; }
}
我已经用 [Required] 装饰了属性。
然后我就有了 MVC Web Api Post 方法
public string Post(Domain.User regModel)
{
return "saved";
}
最后我有我的 Ajax 调用
var user = {
Id: "1",
Email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9adbcaaad99adbcaaadf7bab6b4" rel="noreferrer noopener nofollow">[email protected]</a>",
PasswordHash: "asjdlfkjals;dkjflkjsaldfjsdlkjfiovdfpoifjdsiojfoisj",
IsDeleted: true
};
$.ajax({
type: 'POST',
url: '/api/registration/post',
cache: false,
data: JSON.stringify(user),
crossDomain: true,
contentType: "application/json;charset=utf-8",
success: function (data) {
console.log(data);
}
});
按照要求出错 发布http://localhost.com:11001/api/registration/post 500(内部服务器错误)
<Error>
<script/>
<Message>
The requested resource does not support http method 'GET'.
</Message>
</Error>
我的问题
如果我用 [Required] 装饰我的模型,我会收到错误 500 - 不支持 Get 方法
但是如果我删除它。一切正常。
我真的很想了解为什么 MVC Web API 会出现这种情况。当然我可以创建 View 模型但是。我只是想了解为什么会发生这种情况。
谁能解释一下
谢谢
最佳答案
我似乎找到了一个迟到的原因,因为我已经从 Web api 更改为标准 MVC。 (效果很好,无需解决)您可以在以下链接中找到答案:
asp net web api validation with data annotations
web api nullable required property requires datamember attribute
dataannotation for required property
谢谢大家的帮助
关于ajax - 带有模型装饰的 ASP.NET Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16933910/