从WebAPI2中的ActionFilters返回HttpStatuscode的错误

时间:2018-06-17 01:35:58

标签: c# http asp.net-web-api asp.net-core action-filter

我在WebAPI .netCore环境中,我正在使用ActionFilters来获取一些JWT授权代码。现在,发生任何错误时我的代码如下所示:

context.Result = new JsonResult(new { Error = "JWT Token is expired."});

这段代码的问题在于它仍然会抛出状态码200.我希望它在HTTP级别失败并抛出状态码400.我该怎么做?

1 个答案:

答案 0 :(得分:4)

BadRequestObjectResult将返回400.

public class MyActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        context.Result = new BadRequestObjectResult(new {Error = "JWT Token is expired."});
    }
}