No1Lives4Ever
No1Lives4Ever

Reputation: 6883

Returning HTTP Result Code 404 With a Custom Error Message

I'm have this controller:

[HttpGet]
public ActionResult AjaxCall(string input)
{
    // ...
    if (!success)
    {
        Response.StatusCode = 404;
        ViewBag.Output = ex.Message;
        return View();
    }
    // ...
}

This controller serve some AJAX calls. The web-browser send calls and I'm returning the result by HTTP-ERROR-CODES. I'm using two error-codes: 200 (success), 404 (failed).

This is how my View looks like:

@{
    Layout = null;
}
@Html.Raw(ViewBag.Output)

My View just prints to the page the error message.

Everything looks fine until the page status code returning 404 error code. Then, the code ignore my "ViewBag.Output" message. Instead of my custom message, I'm always getting this message:

The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

No matter which error occurs. As you guess, this is the system default 404 error code message.

How can I return a 404 error code with my custom message?

Upvotes: 0

Views: 2181

Answers (1)

Marcin Zablocki
Marcin Zablocki

Reputation: 10683

If you use AJAX, I suppose that you send some JSON/XML strings or return 404. If so, use string instead of ActionResult as the return type for your action. Furthermore you may find this question helpful: Returning 404 Error ASP.NET MVC 3

Upvotes: 1

Related Questions