8
當我使用ASP.Net MVC 3.0中的HttpStatusCodeResult返回帶有換行符的StatusDescription時,與我的客戶端的連接被強制關閉。應用程序位於IIS 7.0中。爲什麼在ASP.Net中向StatusDescription添加一個換行符會關閉連接?
實施例的控制器:
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");
}
引發的異常:使用捲曲(捲曲7.25.0(I386-PC時
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
的行爲是一致的-win32)libcurl/7.25.0 zlib/1.2.6)
curl http://localhost/app/Foo/MyAction
捲曲:(56)的Recv失敗:連接被重置
編輯
最後我用這個自定義的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();
}
}
很簡潔的答案。 – JJS 2012-08-12 22:59:00