How to return Unathorized from .Net Core Web API

You may return something like this:

return StatusCode(statusCode);

or

return Unauthorized();

Since StatusCode() and Unauthorized() return an ActionResult, you'll want to change your action's return type to IActionResult instead. (Which means while you'll need to return your actual value as Ok(yourValue)).

Example:

public IActionResult GetSomeData()
{
    if(!CheckAccessCondition())
        return Unauthorized();
    return Ok(somevalue);
}

ASP.NET core introduced authorization policies. Read more about it here.


If the only reason you don't have a IActionResult return type is because you want to return json data, you can still return it and do this:

public IActionResult GetSomeData()
{
    if (condition) 
      return Json(myData);
    else 
      return Unauthorized();
}

A little hacky, but you can also simply return null and configure your response using HttpContext

public SomeData GetSomeData()
{
    if (condition) return myData;
    else 
    {
        HttpContext.Response.StatusCode = 401;
        return null;
    }

}

If you need SomeData for some reason such as type safety, one of your options are to set up a filter class.

public class MyAccessAttribute : Attribute, IActionFilter{

    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (condition)
            context.Result = new UnauthorizedResult();
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
    }
}

You can then use it on your action like this:

[MyAccess]
public SomeData GetSomeData(){

Update As of .netcore 2.1 you can now use generic ActionResult

 public ActionResult<SomeData> GetSomeData(){

Logically you have first to change the return type of you method. Then you can handle it as below:

public IActionResult GetSomeData()
{
    if(!CheckAccessCondition()) return HttpUnauthorized();
}