Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3991276
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T06:35:46+00:00 2026-05-20T06:35:46+00:00

I have an MVC 2 app that I want all requests to return json.

  • 0

I have an MVC 2 app that I want all requests to return json. I have overridden a HandleErrorAttribute and an AuthorizeAttribute. My goal is that all errors (even 403 and 404) are returned as json.

Here is my error handler. ExceptionModel is a simple class defining any error returned by my application. The Exception handler is a class that translates the error details into a formatted e-mail and sends it to me.

public class HandleErrorJsonAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        context.ExceptionHandled = true;

        RaiseErrorSignal(context.Exception);

        context.RequestContext.HttpContext.Response.ContentType = "application/json";

        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(context.HttpContext.Response.Output, new ExceptionModel(context.Exception));
    }

    private static void RaiseErrorSignal(Exception ex)
    {
        IExceptionHandler handler = Resolve();

        handler.HandleError(ex.GetBaseException());
    }

    private static IExceptionHandler Resolve()
    {
        return ServiceLocator.Locate<IExceptionHandler>();
    }
}

Here is the Exception model for clarification

public class ExceptionModel
{
    public int ErrorCode { get; set; }
    public string Message { get; set; }

    public ExceptionModel() : this(null)
    {

    }

    public ExceptionModel(Exception exception)
    {
        ErrorCode = 500;
        Message = "An unknown error ocurred";

        if (exception != null)
        {
            if (exception is HttpException)
                ErrorCode = ((HttpException)exception).GetHttpCode();

            Message = exception.Message;
        }
    }

    public ExceptionModel(int errorCode, string message)
    {
        ErrorCode = errorCode;
        Message = message;
    }
}

and finally, my custom authorize attribute. I an using forms auth, but I did not want any of the automatic redirection. I simply want the error to show on the screen and stop any further processing.

public class AuthorizeTokenAttribute : System.Web.Mvc.AuthorizeAttribute
{
    public bool SuperAdminOnly { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        bool authorized = base.AuthorizeCore(httpContext);

        if(!SuperAdminOnly)
            return authorized;

        if(!authorized)
            return authorized;

        return SessionHelper.UserIsSuperAdmin(httpContext.User.Identity.Name);
    }

    protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
    {
        throw new HttpException(403, "Access Denied");
    }
}

This all works great for most errors, but it is missing one thing. I have a controller action like this.

[AuthorizeToken]
[HttpPost]
public JsonResult MyAction()
{
    return new JsonResult();
}

It works fine when you submit via post, but on a get I receive an unhandled 404 error.

Server Error in ‘/’ Application.

The resource cannot be found.

Description: HTTP 404. The resource
you are looking for (or one of its
dependencies) could have been removed,
had its name changed, or is
temporarily unavailable. Please
review the following URL and make sure
that it is spelled correctly.

Requested URL: /MyController/MyAction

Version Information: Microsoft .NET
Framework Version:4.0.30319; ASP.NET
Version:4.0.30319.1

This happens on a GET, which is to be expected as default behavior. However, how can I handle for this condition so that I could instead return json like this

{"ErrorCode":404,"Message":"Page Not Found"}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T06:35:46+00:00Added an answer on May 20, 2026 at 6:35 am

    To handle errors personally I prefer the Application_Error event in Global.asax:

    protected void Application_Error(object sender, EventArgs e)
    {
        var exception = Server.GetLastError();
        Response.Clear();
        Server.ClearError();
    
        var httpException = exception as HttpException;
        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "Index";
        routeData.Values["error"] = exception;
    
        IController errorController = new ErrorsController();
        errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    }
    

    and then have an ErrorsController:

    public class ErrorsController : Controller
    {
        public ActionResult Index(Exception exception)
        {
            var errorCode = 500;
            var httpException = exception as HttpException;
            if (httpException != null)
            {
                errorCode = httpException.ErrorCode;
            }
    
            return Json(new
            {
                ErrorCode = errorCode,
                Message = exception.Message
            }, JsonRequestBehavior.AllowGet);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an MVC app that is working fine, but I now want to
I have an ASP.NET MVC app that stores all SQL DateTime in UTC, so
I have an MVC app that does a lot of work with jQuery ajax
I have an ASP.NET MVC app that opens a Request view in a new
I have an asp.net mvc app that is built to run as standard web
Assume I have an ASP.NET MVC app that's not doing anything too fancy (no
So, I have an asp.net mvc app that is being worked on by multiple
I have a MVC app and using JQuery. I have anchor that I setup
I have an asp.net mvc app running on a local iis website that is
So I have about 10 short css files that I use with mvc app.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.