【问题标题】:HttpException in ASP.NET MVC with EntityFramework and JSON带有 EntityFramework 和 JSON 的 ASP.NET MVC 中的 HttpException
【发布时间】:2017-01-29 17:11:54
【问题描述】:

我想对数据库进行选择。但我收到以下错误(仅错误的第一行):

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below

[HttpException (0x80004005): Server cannot set content type after HTTP headers have been sent.]
   System.Web.HttpResponse.set_ContentType(String value) +9752569
   System.Web.HttpResponseWrapper.set_ContentType(String value) +14
   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +177
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +27

我的 DBcontroller 的一部分:

string sql = @"exec [results].[GetNewResults] '" + Sources + @"', '" + Searchstring + @"', '" + username + @"', '" + sessionid + @"'";
        var result = dbcontext_hke.Database.SqlQuery<UnifiedResultset>(sql);

if (results == null)
{
    Debug.WriteLine("results is null");
    return Json(null);
}

Debug.WriteLine("results isn't null");
Debug.WriteLine(results);
return Json(results, JsonRequestBehavior.AllowGet);

我的js的一部分:

var url = $('#initialrequest').val();
$.ajax({
    url: url,
    data: {sources, searchstring},
    type: 'POST',
})
.success(function (result) {
for (var i = 0; i <= (9); i++) {
    try {
        console.log("lenght of result is :" + result.length);
        add_error(result);
        console.log("result is : " + result);
        add_result(result[i].header, result[i].source, result[i].subsource, result[i].description);
    } catch (err) {
        add_error();
    }
 })
.error(function (xhr, status) {
    $('#error').append(xhr.responseText);
    console.log(xhr.responseText);
});

基本上经过一些研究,我发现this 使用该代码作为(可能)类似问题的解决方案:

this.Context.Response.Write(response);
this.Context.Response.Flush();

谁能向我解释那里发生了什么以及如何修复它(或修改其他解决方案的代码)?

EDIT1:我已确保控制器获取信息。所以错误可能出在控制器和js之间的通信上。有什么想法吗?

EDIT2:同时添加

Response.BufferOutput = true;

在 HomeController 的 Index() 处,DBController 不会改变任何东西。

EDIT3: 我发现问题出在返回的 JSON 上。如果我返回不同的类型,它工作正常。任何想法为什么会发生这种情况以及如何解决它?

EDIT4:我的代码不起作用的原因是因为命令

var result = dbcontext_hke.Database.SqlQuery<UnifiedResultset>(sql);

我认为不会立即执行。如果我想查看 Debug.WriteLine(result) 的内部结果,我只会得到普通的 sql 命令。想法?

【问题讨论】:

  • 你可以找到非常详细的讨论here。我相信您的代码的其他部分会导致这种行为,而不是您所展示的。我看到的唯一嫌疑人是return Json(null) - 不确定这是如何工作的
  • 我不太确定 - 讨论很适合获得概述,但我真的不知道如何解决它。

标签: javascript c# jquery asp.net asp.net-mvc


【解决方案1】:

Andrei 是正确的 - 有另一行导致此错误。 正如stephbu 在他的comment 第3 项中提到的那样:“流是无缓冲的,迫使响应标头在标记写入开始之前被写入。”

这种情况是由线路引起的

Response.Flush();

上面提到的数据库控制器代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    相关资源
    最近更新 更多