【问题标题】:ASP.NET Web API with Decorations on Models带有模型装饰的 ASP.NET Web API
【发布时间】:2013-06-12 14:31:51
【问题描述】:

使用的技术:代码优先、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 发布方法

    public string Post(Domain.User regModel)
    {
        return "saved";
    }

最后我有我的 Ajax 调用

var user = {
Id: "1",
Email: "test@test.com",
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);
}

});

请求错误 POST http://localhost.com:11001/api/registration/post 500(内部服务器错误)

 <Error>
    <script/>
    <Message>
    The requested resource does not support http method 'GET'.
    </Message>
    </Error>

我的问题 如果我用 [Required] 装饰我的模型,我会收到错误 500 - No Get Method Supported 但是,如果我删除它。一切正常。

我真的很想了解为什么 MVC Web API 会出现这种情况。当然我可以创建视图模型但是。我只是想了解为什么会这样。

谁能解释一下

谢谢

【问题讨论】:

  • 你能发布确切的错误信息吗?哪个控制器不支持它所说的 Get 方法?
  • 已添加。它在注册控制器上。我确实有一个 get 方法,但让我感到困惑的是域对象上的装饰。因为当我将它们注释掉时这有效。
  • 虽然您对 API 建模的方式有点不标准,但这应该不是问题。这里的一切看起来都不错。您是否尝试过访问 Web API 源代码?
  • 如果我装饰它,我什至不会在 web api 上打断点。 “尝试访问 Web API 源代码”是什么意思?
  • 我的意思是ASP.NET MVC的源代码可以在这里找到aspnet.codeplex.com/SourceControl/latest

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


【解决方案1】:

我似乎找到了一个迟到的原因,因为我已经从 Web api 更改为标准 MVC。 (完全没有工作要做)您可以在以下链接中找到答案:

asp net web api validation with data annotations

web api nullable required property requires datamember attribute

dataannotation for required property

谢谢大家的帮助

【讨论】:

    【解决方案2】:

    问题可能实际上是您尝试使用Id = "1" 发布用户,而Domain.User 指定 Id 的类型为 Guid。 “1”不是有效的 Guid,因此当该属性标记为 Required 时,它无法调用您的 Post 方法。当您删除所需的属性时,可以使用/调用 Post 方法,因为它只会将 User 对象的 Id 设置为 Null 或空 Guid,因为它不是必需的。

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多