简体   繁体   中英

How to return Unathorized from .Net Core Web API

I do have simple API controller, and I do need to return 401. Method's return type is not IActionResult so I can't just return Unauthorized()

How can I return Unauthorized in this case?

[Produces("application/json")]
public class MyController : Comntroller
{
    public SomeData GetSomeData([FromBody]RequestData data)
    {
        if(!CheckAccessCondition(data, GetCurrentUser()))
            // ?? how to return from here 401
        ///
    }
}

Update :

  1. Using IActionResult is not a way. It is not type safe from one side, and would not allow to generate C# & Typescript clients for my API (now i'm using NSwag for this purpose)
  2. It would be great to avoid throwing exception because of performance (throwing exception is really expensive operation)
  3. Some update about checking access condition - I do need to check if authorized user has right to manipulate with request data. So for using some "authorization-like" attribute it would be great to do the check after request data was deserialized (to avoid double deserialization, once again - because of performance)

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(){

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 .

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM