如何在ASP.NET MVC 3.0通过JSON返回出错正确的响应? [英] How to return correct response on error in ASP.NET MVC 3.0 via JSON?
问题描述
我挣扎来解决这个问题。在我的本地机器(Win7的/ VS2010 / IIS 7.5)和另一个相同开发人员的机器,下面的code返回500状态code和响应文本说无法找到与指定的电子邮件地址的用户。
I'm struggling to resolve this problem. On my local machine (Win7/VS2010/IIS 7.5) and another identical developer's machine, the following code returns the 500 status code, and the response text says "Could not locate user with specified email address".
在我的网站部署到我的测试服务器(R2的Win2008 / IIS7.5),它返回正确的状态code,但内容类型设置为text / html的和responseText的不包含消息。
When I deploy the site to my test server (Win2008 R2/IIS7.5) it returns the correct status code, but the content type is set to "text/html" and the responseText doesn't contain the message.
我已经试过了服务器,它没有什么区别的关闭自定义错误。任何人都可以发现这个问题可能是什么?
I've tried turning off custom errors on the server, which made no difference. Can anyone spot what the problem could be?
我有一个使用AjaxHelper.BeginForm方法构成的方式:
I have a form that is configured using the AjaxHelper.BeginForm method:
@using (Ajax.BeginForm("FindUser", new AjaxOptions {OnSuccess="findComplete", OnFailure="findFailed"})
{
<fieldset>
@Html.EditorFor(m => m.UserEmail)
<div class="form-item button search">
<input type="submit" value="Find"/>
</div>
<div id="find-err" class="message error hidden">
<div class="contents"></div>
</div>
</fieldset>
}
通过一个错误处理JavaScript函数:
With an error handling javascript function:
function findFailed(result) {
var error = result.responseText;
if (error) {
$('#find-err .contents').text(error).slideDown();
}
}
控制器动作捕捉任何错误,并返回一个信息:
The controller action catches any errors and returns a message:
[HttpPost]
public ActionResult FindUser(FindUserModel model)
{
try
{
// code to find user
if (user == null)
{
throw new Exception("Could not locate user with specified email address.");
}
if (Request.IsAjaxRequest())
{
return Json(new { id = user.Id, name = user.Name }, JsonRequestBehavior.AllowGet);
}
model.FoundUser = user;
return View("Details", model);
}
catch (Exception ex)
{
if (Request.IsAjaxRequest())
{
Response.StatusCode = 500;
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
ModelState.AddModelError("UserEmail", ex.Message);
return View(model);
}
}
任何帮助将是非常美联社preciated:)
Any help would be much appreciated :)
推荐答案
看起来像IIS吃响应,并尝试做它的自定义错误的东西吧。
Looks like IIS is eating the response and trying to do it's custom error stuff with it.
尝试设置
Response.TrySkipIisCustomErrors = true
在你钓到的鱼。
另外设置以下配置值:
<httpErrors errorMode="Custom" existingResponse="PassThrough"/>
这篇关于如何在ASP.NET MVC 3.0通过JSON返回出错正确的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!