Home > Enterprise >  Return individual error message after an ajax call in ASP.NET MVC 5
Return individual error message after an ajax call in ASP.NET MVC 5

Time:01-27

When I send an ajax request to the server, I want to return an individual message to the client in the responseText in case of an error. In debug mode on my development machine this works fine. Unfortunately, in production mode on the web server I always get an error message "Bad Request" but no longer the individual message. I am developing my application in ASP.NET MVC 5 and I am using jQuery 3.6.0.

My ajax request looks like this:

$.ajax({
    type: 'POST',
    url: 'myURL',
    data: {
        val1: clientVal1,
        val2: clientVal2
    },
    success: function (res) {
        //do smthg...
    },
    error: function (response) {
        alert(response.responseText);
    }
});

On the server side, I take the ajax call like this:

[HttpPost]
public ActionResult myURL(string val1, string val2)
{
    if(val1.contains(val2))
    {
                        
    }
    else
    {
        Response.StatusCode = 400;
        Response.Write("My custom error msg.");
        return new HttpStatusCodeResult(400);
    }
    return Json(new { someVal1, otherVal2}, JsonRequestBehavior.AllowGet);
}

The httperrors in my webconfig file look like this:

<httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" subStatusCode="-1" />
    <remove statusCode="403" subStatusCode="-1" />
    <remove statusCode="500" subStatusCode="-1" />
    <error statusCode="404" path="/ErrorHandling/http404" responseMode="ExecuteURL" />
    <error statusCode="403" path="/ErrorHandling/http403" responseMode="ExecuteURL" />
    <error statusCode="500" path="/ErrorHandling/http500" responseMode="ExecuteURL" />
</httpErrors>

What am I doing wrong?

CodePudding user response:

I have found the solution. First I had to move the redirection to the individual error pages in the web.config to the <system.web> area. Now my system.web area looks like this ([...] means that there are other settings which are not relevant for this):

<system.web>
    [...]
    <customErrors mode="On" redirectMode="ResponseRedirect" defaultRedirect="/ErrorHandling/http500">
        <error statusCode="404" redirect="/ErrorHandling/http404" />
        <error statusCode="403" redirect="/ErrorHandling/http403" />
        <error statusCode="500" redirect="/ErrorHandling/http500" />
    </customErrors>
    [...]   
</system.web>

After that, I had to change the system.webServer section as suggested in the post by freedomn-m and suggested by Rahul Sharam as follows:

<httpErrors errorMode="Custom" existingResponse="PassThrough">
</httpErrors>

Now everything works as it should.

  •  Tags:  
  • Related