ajax - 带有模型装饰的 ASP.NET Web API

标签 ajax asp.net-web-api code-first

使用的技术: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/

相关文章:

php - 使用ajax为每个输入字段更新mysql中的数据

javascript - 通过 if 语句评估后 AJAX 无输出

c# - 从 C# MVC 模型设置 AngularJS $provide.constant 值的最佳方法是什么?

asp.net-mvc-4 - 在选中的复选框中发布表单时,ModelState 无效

c# - 当我有一个实体时,动态地在 DbContext 中查找指定的通用 DbSet

entity-framework - 没有发生并发检查

jquery - 如何使用 jquery 从选择框中获取一堆选定的 id

javascript - MobileSafari 不会发回使用 CORS 设置的 Cookie

asp.net-web-api - 如何在ConfigureServices方法中获取IOptions或将IOptions传递到扩展方法中?

ef-code-first - 使用连接字符串进行代码优先迁移