[英]ActionFilter Return Http Status Code with Message
I have an ActionFilterAttribute
in which I am checking for a valid license.我有一个
ActionFilterAttribute
,我正在其中检查有效的许可证。 I would like to return a 401 error along with a message.我想返回 401 错误和一条消息。 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 ): GitHub 上提供了 ASP.NET Core 源代码,这意味着我们可以看到控制器中使用的
Unauthorized
方法的实现如下所示( source ):
public virtual UnauthorizedObjectResult Unauthorized([ActionResultObjectValue] object value)
=> new UnauthorizedObjectResult(value);
You can emulate this inside of your OnActionExecuting
implementation, like this:您可以在
OnActionExecuting
实现中模拟这一点,如下所示:
context.Result = new UnauthorizedObjectResult("Some error message");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.