Your api endpoint accepts a request with valid request body (determined by [FromBody]
decorated on the input string email
) but your request is posted with the default contentType
of application/x-www-form-urlencoded
(by $.ajax
). That results in an empty request body sent.
So you have 2 options, either remove the [FromBody]
or post the ajax request with a content type of application/json
. With that content type, the whole string passed to data
option will be sent via the request body. The server-side code will parse that request body using a json serializer formatter (input formatter) because the content-type
header value is application/json
.
Here is the how you follow the second option (posting json request):
$.ajax({
type: "POST",
url: '../../api/UserEntities/insertEmail',
contentType: 'application/json',
data: data.email,
success: function () {
//...
}
});
NOTE: the above code we don't use JSON.stringify
because it's unnecessary. Your server-side model is just a string
. In case of using JSON.stringify
, you need to update your model to use a class like this:
//just an example to help you understand
public class DataModel {
[JsonProperty("email")]
public string Email {get;set;}
}
//update your Insert method to this
public void Insert([FromBody] DataModel data)
{
//accessing data.Email
}
//then you can use JSON.stringify to post the json of your email object
$.ajax({
type: "POST",
url: '../../api/UserEntities/insertEmail',
contentType: 'application/json',
data: JSON.stringify(data),
success: function () {
//...
}
});
References:
FromBodyAttribute
Input formatters
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…