简体   繁体   English

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

[英]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.

相关问题 如何返回 http 错误状态代码以及 class 中的自定义消息 - How to return http error status code along with custom message in a class 如何在IEnumerable中返回自定义HTTP状态代码+消息 <xxx.Models.xxx> 功能 - How to return Custom HTTP Status code + message in IEnumerable<xxx.Models.xxx> function 向浏览器返回正确的http错误状态代码 - Return correct http error status code to browser 如何返回自定义 http 状态码 CoreWCF? - How to return custom http status code CoreWCF? 如何在ServiceStack中返回不同的Http状态码 - How to return different Http Status Code in ServiceStack 从WebAPI返回自定义HTTP状态代码? - Return Custom HTTP Status Code from WebAPI? await 使 http 请求返回状态码 0 - await makes http request return status code 0 向AJAX返回错误消息以及HTTP状态代码 - Returning error message to AJAX as well as HTTP status code 将此消息发送到您的机器人时出错:HTTP状态代码InternalServerError - There was an error sending this message to your bot: HTTP status code InternalServerError “向您的机器人发送此消息时出错:HTTP 状态代码未找到” - “There was an error sending this message to your bot: HTTP status code NotFound”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM