I'm learning web api with jquery.
Here is my plugin to make a post request:
$.postAPI = function (url, data) {
let defer = $.Deferred();
let onSuccess = function (data) {
defer.resolve(data);
};
let onError = function (error) {
defer.reject(error);
};
$.ajax({
url: url,
method: 'POST',
data: data || null
}).done(onSuccess).fail(onError);
return defer;
};
API controller:
[Route("api/user")]
public class UserApiController : Controller
{
[HttpPost("{userid?}")]
public IActionResult GetData(string userid)
{
if (!string.IsNullOrEmpty(userid))
{
return Ok(userid);
}
return new StatusCodeResult(401);
// also try with
// return BadRequest();
// return Unauthorized();
}
}
Testing:
$.postAPI('/api/user/getdata').done(function (data) {
console.log('success:', data);
}).fail(function (e) { console.log('fail:', e); });
But I have always got this log:
success: getdata
I want to make the request becomes fail
. So, the log may be:
fail: ...
My question: How can I do that?
UPDATE:
I've tried to add this line (based on the comment):
Response.StatusCode = 404;
to the method. But the problem wasn't solved.