10

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 :)

1 Answer 1

15

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"/>
Sign up to request clarification or add additional context in comments.

1 Comment

Nice one, hadn't considered IIS custom errors getting in the way. My HandleErrorsAttribute sets TrySkipCustomErrors, but when directly returning the status with a JSON response, I wasn't setting it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.