簡體   English   中英

如何在ActionExecutionContext中修改HttpContext以拒絕帶有正文的請求?

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

ActionExecutionContext是在ActionFilter屬性中定義的。

例:

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

         context.HttpContext.Response.StatusCode = 400;

         //context.HttpContext.Response.Body 
     }
 }

如何使ActionExecutionContext的 HttpContext的響應具有狀態代碼400(錯誤請求),並且還具有諸如“您無權訪問”的正文。

在ASP.NET中,您可以使用以下代碼輕松完成此操作:

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

您可以使用以下方法定義狀態代碼

ActionExecutionContext.HttpContext.Response.StatusCode = 400;

但是內容如何呢?這真的是最好的方法-手動輸入狀態碼嗎?

正如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