简体   繁体   中英

ActionFilter Return Http Status Code with Message

I have an ActionFilterAttribute in which I am checking for a valid license. I would like to return a 401 error along with a message. Right now, I have the following implementation:

public override void OnActionExecuting(ActionExecutingContext context) {
    ...
    // return errror (short-circuit)
    context.Result = new StatusCodeResult(401);
    return;
}

How can I also pass a message? Inside my controllers, I would do the following:

return Unauthorized("Some error message");

The ASP.NET Core source code is available on GitHub, which means we can see that the implementation for the Unauthorized method used in a controller looks like this ( source ):

public virtual UnauthorizedObjectResult Unauthorized([ActionResultObjectValue] object value)
    => new UnauthorizedObjectResult(value);

You can emulate this inside of your OnActionExecuting implementation, like this:

context.Result = new UnauthorizedObjectResult("Some error message");

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