Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 512
ili Avatar asked Sep 13 '17 04:09

ili


People also ask

How do I return HTTP response messages in web API?

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).

How do I return XML and JSON from web API in .NET core?

In order to return XML using an IActionResult method, you should also use the [Produces] attribute, which can be set to “application/xml” at the API Controller level. [Produces("application/xml")] [Route("api/[controller]")] [ApiController] public class LearningResourcesController : ControllerBase { ... }

Can we return view from web API?

You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.


1 Answers

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(){
like image 106
Neville Nazerane Avatar answered Oct 12 '22 15:10

Neville Nazerane