gpt4 book ai didi

c# - 在 ASP.NET MVC2 中将 http 204 "no content"返回给客户端

转载 作者:行者123 更新时间:2023-12-01 18:00:14 26 4
gpt4 key购买 nike

在我拥有的 ASP.net MVC 2 应用程序中,我想对后期操作返回 204 No Content 响应。当前我的 Controller 方法具有 void 返回类型,但这会将响应发送回客户端,内容为 200 OK,Content-Length header 设置为 0。如何将响应转换为 204?

[HttpPost]
public void DoSomething(string param)
{
// do some operation with param

// now I wish to return a 204 no content response to the user
// instead of the 200 OK response
}

最佳答案

在MVC3中有一个HttpStatusCodeResult class 。您可以为 MVC2 应用程序推出自己的应用程序:

public class HttpStatusCodeResult : ActionResult
{
private readonly int code;
public HttpStatusCodeResult(int code)
{
this.code = code;
}

public override void ExecuteResult(System.Web.Mvc.ControllerContext context)
{
context.HttpContext.Response.StatusCode = code;
}
}

你必须像这样改变你的 Controller 方法:

[HttpPost]
public ActionResult DoSomething(string param)
{
// do some operation with param

// now I wish to return a 204 no content response to the user
// instead of the 200 OK response
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
}

关于c# - 在 ASP.NET MVC2 中将 http 204 "no content"返回给客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4513583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com