ActionFilter 返回带有消息的 Http 状态代码

Tom*_*adi 6 c# asp.net-core-mvc asp.net-core

我有一个ActionFilterAttribute正在检查有效许可证的文件。我想返回 401 错误以及一条消息。现在,我有以下实现:

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

我也可以如何传递消息?在我的控制器中,我会执行以下操作:

return Unauthorized("Some error message");
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 6

ASP.NET Core 源代码可在 GitHub 上找到,其中显示Unauthorized控制器中使用的方法的实现如下所示(源代码):

public virtual UnauthorizedObjectResult Unauthorized([ActionResultObjectValue] object value)
    => new UnauthorizedObjectResult(value);
Run Code Online (Sandbox Code Playgroud)

您可以在实现中模拟这一点OnActionExecuting,如下所示:

context.Result = new UnauthorizedObjectResult("Some error message");
Run Code Online (Sandbox Code Playgroud)