Search code examples
c#asp.net-mvcasp.net-coreaction-filter

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


The ActionExecutionContext is defined in a ActionFilter attribute.

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."

In ASP.NET you could easily do this with the following code:

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?


Solution

  • As suggested by dropoutcoder and stuartd, both approaches are valid and work perfectly!

    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");
        }
    }