RequiredAttribute and JsonSerializationException in WebApi2
According to Model Validation in ASP.NET Web API, RequiredAttribute should have no effect on a missing non-nullable parameter during model validation.
"Under-posting":
Here, the client did not specify values for Price or Weight. The JSON
formatter assigns a default value of zero to the missing properties.
The model state is valid, because zero is a valid value for these
properties.
I'm updating a piece of code that has [Required] marked on a property like so:
public class Thing
{
[Required]
public int Id { get; set; }
}
and the controller method:
public HttpResponseMessage PutThing(Thing thing)
{
if (ModelState.IsValid)
{
if (thing.Id == 0) // Create
{}
else // Update
{}
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
If I debug the controller code, I can see the "thing.id" is set to 0, but ModelState.IsValid is false, with the following error:
400 BadRequest - Thing.PutThing - {"thing":{"Errors":[{"Exception":{"ClassName":"
Newtonsoft.Json.JsonSerializationException","Message":"Required property 'Id' not found in JSON. Path '', line 1, position 332
Am I missing something about how this works?
It seems like this is an improper use of the [Required] attribute based on the way the controller method is using the "id" property anyway, but I'd just like to know why I'm getting a different behavior than what the docs say.
EDIT: I forgot to mention that, if I don't check ModelState.IsValid, the above code works fine, and sees that thing.Id is 0.
asp.net-web-api2
add a comment |
According to Model Validation in ASP.NET Web API, RequiredAttribute should have no effect on a missing non-nullable parameter during model validation.
"Under-posting":
Here, the client did not specify values for Price or Weight. The JSON
formatter assigns a default value of zero to the missing properties.
The model state is valid, because zero is a valid value for these
properties.
I'm updating a piece of code that has [Required] marked on a property like so:
public class Thing
{
[Required]
public int Id { get; set; }
}
and the controller method:
public HttpResponseMessage PutThing(Thing thing)
{
if (ModelState.IsValid)
{
if (thing.Id == 0) // Create
{}
else // Update
{}
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
If I debug the controller code, I can see the "thing.id" is set to 0, but ModelState.IsValid is false, with the following error:
400 BadRequest - Thing.PutThing - {"thing":{"Errors":[{"Exception":{"ClassName":"
Newtonsoft.Json.JsonSerializationException","Message":"Required property 'Id' not found in JSON. Path '', line 1, position 332
Am I missing something about how this works?
It seems like this is an improper use of the [Required] attribute based on the way the controller method is using the "id" property anyway, but I'd just like to know why I'm getting a different behavior than what the docs say.
EDIT: I forgot to mention that, if I don't check ModelState.IsValid, the above code works fine, and sees that thing.Id is 0.
asp.net-web-api2
add a comment |
According to Model Validation in ASP.NET Web API, RequiredAttribute should have no effect on a missing non-nullable parameter during model validation.
"Under-posting":
Here, the client did not specify values for Price or Weight. The JSON
formatter assigns a default value of zero to the missing properties.
The model state is valid, because zero is a valid value for these
properties.
I'm updating a piece of code that has [Required] marked on a property like so:
public class Thing
{
[Required]
public int Id { get; set; }
}
and the controller method:
public HttpResponseMessage PutThing(Thing thing)
{
if (ModelState.IsValid)
{
if (thing.Id == 0) // Create
{}
else // Update
{}
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
If I debug the controller code, I can see the "thing.id" is set to 0, but ModelState.IsValid is false, with the following error:
400 BadRequest - Thing.PutThing - {"thing":{"Errors":[{"Exception":{"ClassName":"
Newtonsoft.Json.JsonSerializationException","Message":"Required property 'Id' not found in JSON. Path '', line 1, position 332
Am I missing something about how this works?
It seems like this is an improper use of the [Required] attribute based on the way the controller method is using the "id" property anyway, but I'd just like to know why I'm getting a different behavior than what the docs say.
EDIT: I forgot to mention that, if I don't check ModelState.IsValid, the above code works fine, and sees that thing.Id is 0.
asp.net-web-api2
According to Model Validation in ASP.NET Web API, RequiredAttribute should have no effect on a missing non-nullable parameter during model validation.
"Under-posting":
Here, the client did not specify values for Price or Weight. The JSON
formatter assigns a default value of zero to the missing properties.
The model state is valid, because zero is a valid value for these
properties.
I'm updating a piece of code that has [Required] marked on a property like so:
public class Thing
{
[Required]
public int Id { get; set; }
}
and the controller method:
public HttpResponseMessage PutThing(Thing thing)
{
if (ModelState.IsValid)
{
if (thing.Id == 0) // Create
{}
else // Update
{}
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
If I debug the controller code, I can see the "thing.id" is set to 0, but ModelState.IsValid is false, with the following error:
400 BadRequest - Thing.PutThing - {"thing":{"Errors":[{"Exception":{"ClassName":"
Newtonsoft.Json.JsonSerializationException","Message":"Required property 'Id' not found in JSON. Path '', line 1, position 332
Am I missing something about how this works?
It seems like this is an improper use of the [Required] attribute based on the way the controller method is using the "id" property anyway, but I'd just like to know why I'm getting a different behavior than what the docs say.
EDIT: I forgot to mention that, if I don't check ModelState.IsValid, the above code works fine, and sees that thing.Id is 0.
asp.net-web-api2
asp.net-web-api2
edited Nov 27 '18 at 3:42
UnknownBeef
asked Nov 27 '18 at 1:49
UnknownBeefUnknownBeef
306
306
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
[Required] means you are forcing the client to send that value. In your case the Web api converts your json and initializes Thing.Id to 0 but it wasn't sent by the client so the model is invalid. If you do not want to force the client to sent the value of Id remove [required] on top of Id in the model. Another thing you can do is sending 0 from the client when you want to create and a different value when you want to update.
I don't know why you are coupling those two actions, but according to me you should have separate actions for creating and for updating.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53491619%2frequiredattribute-and-jsonserializationexception-in-webapi2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
[Required] means you are forcing the client to send that value. In your case the Web api converts your json and initializes Thing.Id to 0 but it wasn't sent by the client so the model is invalid. If you do not want to force the client to sent the value of Id remove [required] on top of Id in the model. Another thing you can do is sending 0 from the client when you want to create and a different value when you want to update.
I don't know why you are coupling those two actions, but according to me you should have separate actions for creating and for updating.
add a comment |
[Required] means you are forcing the client to send that value. In your case the Web api converts your json and initializes Thing.Id to 0 but it wasn't sent by the client so the model is invalid. If you do not want to force the client to sent the value of Id remove [required] on top of Id in the model. Another thing you can do is sending 0 from the client when you want to create and a different value when you want to update.
I don't know why you are coupling those two actions, but according to me you should have separate actions for creating and for updating.
add a comment |
[Required] means you are forcing the client to send that value. In your case the Web api converts your json and initializes Thing.Id to 0 but it wasn't sent by the client so the model is invalid. If you do not want to force the client to sent the value of Id remove [required] on top of Id in the model. Another thing you can do is sending 0 from the client when you want to create and a different value when you want to update.
I don't know why you are coupling those two actions, but according to me you should have separate actions for creating and for updating.
[Required] means you are forcing the client to send that value. In your case the Web api converts your json and initializes Thing.Id to 0 but it wasn't sent by the client so the model is invalid. If you do not want to force the client to sent the value of Id remove [required] on top of Id in the model. Another thing you can do is sending 0 from the client when you want to create and a different value when you want to update.
I don't know why you are coupling those two actions, but according to me you should have separate actions for creating and for updating.
answered Nov 27 '18 at 4:10
LeMAKLeMAK
161
161
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53491619%2frequiredattribute-and-jsonserializationexception-in-webapi2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown