gpt4 book ai didi

asp.net - 为什么在 ASP.Net 中向 StatusDescription 添加换行符会关闭连接?

转载 作者:行者123 更新时间:2023-12-04 03:29:30 25 4
gpt4 key购买 nike

当我使用 ASP.Net MVC 3.0 中的 HttpStatusCodeResult 返回带有换行符的 StatusDescription 时,与我的客户端的连接被强制关闭。应用程序托管在 IIS 7.0 中。

示例 Controller :

 public class FooController : Controller
{
public ActionResult MyAction()
{
return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest, "Foo \n Bar");
}
}

示例客户端:
using (WebClient client = new WebClient())
{
client.DownloadString("http://localhost/app/Foo/MyAction");
}

抛出异常:
System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. 
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

使用 curl (curl 7.25.0 (i386-pc-win32) libcurl/7.25.0 zlib/1.2.6) 时的行为是一致的

curl http://localhost/app/Foo/MyAction



curl:(56)接收失败:连接已重置

编辑

我最终使用此自定义 ActionResult 来获得所需的结果。
public class BadRequestResult : ActionResult
{
private const int BadRequestCode = (int)HttpStatusCode.BadRequest;
private int count = 0;

public BadRequestResult(string errors)
: this(errors, "")
{
}

public BadRequestResult(string format, params object[] args)
{
if (String.IsNullOrEmpty(format))
{
throw new ArgumentException("format");
}

Errors = String.Format(format, args);

count = Errors.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Length;
}

public string Errors { get; private set; }

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;
response.TrySkipIisCustomErrors = true;
response.StatusCode = BadRequestCode;
response.StatusDescription = String.Format("Bad Request {0} Error(s)", count);
response.Write(Errors);
response.End();
}
}

最佳答案

HTTP header 中间不能有换行符。

HTTP 协议(protocol)指定 header 的结尾是换行符。

由于换行符位于 header 中间,因此 header 不是有效 header ,您会收到此错误。

修复:不要在 HTTP header 中间放置换行符。

关于asp.net - 为什么在 ASP.Net 中向 StatusDescription 添加换行符会关闭连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917212/

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