2

Technology Used: Code First,ASP.NET Web API (restful service) and HTML.

For code first I have a domain Object called 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; }
}

And I have decorated the properties with [Required].

Then I have my MVC Web Api Post Method

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

and lastly I have my Ajax Call

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);
}

});

Error As Requested POST http://localhost.com:11001/api/registration/post 500 (Internal Server Error)

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

My Problem If I decorate my Model with [Required] I get an Error 500 - No Get Method Supported however if I remove that. Everything works well.

I just really want to understand why this is the case with MVC Web API. sure I can create view models but. I just want to understand why this is happening.

Can someone please explain

Thanks

4

2 回答 2

2

I seem to have found a reason why abit late as I already changed from a web api to a standard MVC. (which works perfectly no work around to be done) you can find the answer in the following links:

asp net web api validation with data annotations

web api nullable required property requires datamember attribute

dataannotation for required property

Thank you all for your help

于 2013-06-12T06:31:51.473 回答
0

Could the problem actually be that you are trying to Post a user with Id = "1" while Domain.User specifies that Id is of type Guid. A "1" does not make a valid Guid, so when that property is marked with Required it can't make the call to your Post method. When you remove the required attribute, the Post method can be used/called, because it will just set the Id of the User object to Null or an empty Guid, as it is not required.

于 2013-06-05T19:22:23.050 回答