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?
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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.