.Net MVC4-如何以json格式返回异常?
我有一个MVC4应用程序,其中我使用jQuery从javascript调用控制器操作。当控制器中发生异常时,返回的响应文本为HTML格式。我希望它是JSON格式的。如何做到这一点 我想一些JSON格式化程序应该自己来做这个魔术 JavaScript.Net MVC4-如何以json格式返回异常?,.net,ajax,json,exception,asp.net-mvc-4,.net,Ajax,Json,Exception,Asp.net Mvc 4,我有一个MVC4应用程序,其中我使用jQuery从javascript调用控制器操作。当控制器中发生异常时,返回的响应文本为HTML格式。我希望它是JSON格式的。如何做到这一点 我想一些JSON格式化程序应该自己来做这个魔术 JavaScript // Call server to load web service methods $.get("/Pws/LoadService/", data, function (result) { // Do stuff here }, "json
// Call server to load web service methods
$.get("/Pws/LoadService/", data, function (result) {
// Do stuff here
}, "json")
.error(function (error) { alert("error: " + JSON.stringify(error)) });
.Net控制器操作
[HttpGet]
public JsonResult LoadService(string serviceEndpoint)
{
// do stuff that throws exception
return Json(serviceModel, JsonRequestBehavior.AllowGet);
}
实际上,您将在error函数中跟踪的错误与请求有关,而与应用程序的错误无关 因此,我将在Json结果中传递错误详细信息,如下所示:
try {
//....
return Json(new {hasError=false, data=serviceModel}, JsonRequestBehavior.AllowGet);
}
catch(Exception e) {
return Json(new {hasError=true, data=e.Message}, JsonRequestBehavior.AllowGet);
}
$.get("/Pws/LoadService/", data, function (result) {
var resultData = result.d;
if(resultData.hasError == true) {
//Handle error as you have the error's message in resultData.data
}
else {
//Process with the data in resultData.data
}
}, "json") ...
在客户机中,您可以处理类似的事情:
try {
//....
return Json(new {hasError=false, data=serviceModel}, JsonRequestBehavior.AllowGet);
}
catch(Exception e) {
return Json(new {hasError=true, data=e.Message}, JsonRequestBehavior.AllowGet);
}
$.get("/Pws/LoadService/", data, function (result) {
var resultData = result.d;
if(resultData.hasError == true) {
//Handle error as you have the error's message in resultData.data
}
else {
//Process with the data in resultData.data
}
}, "json") ...
这就是我以前解决这个问题的方法。我认为在将JsonResult指定为返回类型时,框架将以Json格式返回异常。也许我可以将http头设置为application/json并获得json结果?我将此设置为答案,因为我认为这是一个众所周知的解决方案。