简体   繁体   English

如何在ActionExecutionContext中修改HttpContext以拒绝带有正文的请求?

[英]How to modify HttpContext in ActionExecutionContext to deny the request with a body?

The ActionExecutionContext is defined in a ActionFilter attribute . ActionExecutionContext是在ActionFilter属性中定义的。

Example: 例:

 internal class TestAttribute : ActionFilterAttribute
 {
     public override void OnActionExecuting(ActionExecutingContext context)
     {

         context.HttpContext.Response.StatusCode = 400;

         //context.HttpContext.Response.Body 
     }
 }

How do you make the response of the ActionExecutionContext's HttpContext have status code 400 (Bad Request), and to also have a body of for example "You have no access." 如何使ActionExecutionContext的 HttpContext的响应具有状态代码400(错误请求),并且还具有诸如“您无权访问”的正文。

In ASP.NET you could easily do this with the following code: 在ASP.NET中,您可以使用以下代码轻松完成此操作:

HttpActionContext.Response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
   Content = "You have no access.";
}

You can define the status code by using 您可以使用以下方法定义状态代码

ActionExecutionContext.HttpContext.Response.StatusCode = 400;

but what about the contents, and is this really the best approach - to manually write in the status code number? 但是内容如何呢?这真的是最好的方法-手动输入状态码吗?

As suggested by dropoutcoder and stuartd , both approaches are valid and work perfectly! 正如dropoutcoderstuartd所建议的那样 ,两种方法都是有效的,并且可以完美地工作!

internal class TestAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Suggested by dropoutcoder
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.WriteAsync("You have no access").Wait();
        context.HttpContext.Response.StatusCode = 400;

        // Suggested by stuartd
        context.Result = new BadRequestObjectResult("You have no access");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM