Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return correct response on error in ASP.NET MVC 3.0 via JSON?

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".

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?

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>
}

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);
    }
}

Any help would be much appreciated :)

like image 632
James Simm Avatar asked Jun 23 '11 15:06

James Simm


People also ask

What is return JSON in MVC?

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format.

How do I return JSON from action method?

To return JSON (JavaScript Object Notation) content from controller, we use JsonResult return type in the action method of the controller.

How can show error message in ASP.NET MVC?

You can use the standard ASP.NET MVC ValidationSummary method to render a placeholder for the list of validation error messages. The ValidationSummary() method returns an unordered list (ul element) of validation messages that are in the ModelStateDictionary object.


1 Answers

Looks like IIS is eating the response and trying to do it's custom error stuff with it.

Try setting

Response.TrySkipIisCustomErrors = true

in your catch.

Alternatively set the following config value:

<httpErrors errorMode="Custom" existingResponse="PassThrough"/>
like image 187
Rob Stevenson-Leggett Avatar answered Sep 16 '22 16:09

Rob Stevenson-Leggett