0

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.

Snapshot: 1

2 Answers2

0

Try this:

[HttpPost("{userid?}")]
public IActionResult GetData(string userid)
{
    if (!string.IsNullOrEmpty(userid))
    {
        return View(new ViewModel(userid));
    }

    return StatusCode(401);
}
silkfire
  • 24,585
  • 15
  • 82
  • 105
0

If you call "api/user" this will directly call your function "GetData" because you have no route for the function defined.

The "getdata" part in the url api/user/getdata will be interpreted as your "userid" therefor if (!string.IsNullOrEmpty(userid)) will always return true.

If you call "api/user" without the "getdata" part it should fail.

If you want to keep using getdata as url you can add a route for the function like so:

[HttpPost("GetData/{userId?}")]
public IActionResult GetData(string userid)
{
    if (!string.IsNullOrEmpty(userid))
    {
        return Ok(userid);
    }
    return BadRequest();
}

See: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing

Mike Bovenlander
  • 5,236
  • 5
  • 28
  • 47
  • Thank you! It's working. Can I have another question? After I change `BadRequest` to `Unauthorized`, why does the log still throw `404` error?. Image: http://i.imgur.com/o4DNsns.png –  May 05 '17 at 13:42
  • I mean: the status code should be 401 instead of 404 –  May 05 '17 at 13:43
  • Could be that routing is case sensitive: try `[HttpPost("getdata/{userId?}")]` – Mike Bovenlander May 05 '17 at 13:44