Return message together with Unauthorizedresult

Asked

Viewed 593 times

4

I am 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 requests and act according to a number of business rules. It is worth pointing out that I cannot change the API itself, so the approach chosen was this. For such, 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 use case, I need to block unauthorized requests due to lack of token necessary. 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 entering the validation merit of the token, this is enough for my request to be blocked. However, I need that, along with code 401, a JSON containing an error message is returned, something like

{
    "error": "unauthorized"
}

I tried to follow that answer, but the equivalent of Content in Core - at least as far as I know - does not receive parameters in the constructor. The constructor of UnauthorizedResult not either. I tried to create my answer manually, something on the line:

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 proper code and error message?

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;  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.