Return message along with UnauthorizedResult

3

I'm using .NET Core 2 to create a dependency that will be injected into an API. The idea is to create a middleware to control incoming requisitions and act on a set of business rules. It is worth pointing out that I can not change the API itself, so the chosen approach was this. For that, I am implementing the interface IActionFilter

public class RequestsFilter: IActionFilter
{

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // code
    }


    public void OnActionExecuting(ActionExecutingContext context)
    {
        // code
    }
}

In a simple-to-use case, I need to block unauthorized requests due to the lack of token required. I can return the corresponding HTTP code as follows:

 public void OnActionExecuting(ActionExecutingContext context)
 {
     var _token = context.HttpContext.Request.Headers["Authorization"];

     if (String.IsNullOrEmpty(_token))
     {
         context.Result = new UnauthorizedResult();
     }
 }

Without getting into the validation merit of token , this is enough for my request to be blocked. However, I need to have a JSON containing an error message with the 401 code returned, something like

{
    "error": "unauthorized"
}

I tried to follow this answer , but the equivalent of Content in Core -  at least as far as I know - does not get parameters in the constructor. The constructor of UnauthorizedResult does not. I tried to create my answer manually, something along the lines of:

context.HttpContext.Response.StatusCode = 401;
// ...

But the return is still 200, and the request goes smoothly. What am I doing wrong? What is missing? How do I return the appropriate code and error message?

    
asked by anonymous 12.09.2017 / 16:43

1 answer

2

create an ObjectResult, with it you can return any object next to the error code.

var result = new ObjectResult(new{erro ="você precisa ser admin"});  
result.StatusCode = 401;  
context.Result = result;  
return;  
    
18.09.2017 / 14:42