0

I'm trying to setup my controllers so that they can use http error codes to send the responses to ajax calls. So for example I have my login ajax call and controller action:

[System.Web.Mvc.HttpPost, System.Web.Mvc.AllowAnonymous]
public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
{
    [...]
    var loginError = new HttpResponseMessage(HttpStatusCode.Unauthorized)
    {
        Content = new StringContent("Lorem ipsum 2 " + ErrorMessages.LOGINERROR),
        ReasonPhrase = "Lorem ipsum 2 " + ErrorMessages.LOGINERROR
    };
    throw new HttpResponseException(loginError);
}

$.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: "text",
    success: callBack,
    error: function () { console.log("Error..."); },
    statusCode : {
        401: function (result) {
            console.log("Login failed (401): " + result);
        }
    }
});

I'm thinking there are a couple of things I'm not doing right, if someone can point them out that would be lovely!

Thanks!

Sébastien Richer
  • 1,642
  • 2
  • 17
  • 38

2 Answers2

1

Instead of throw exception just return ActionResult that provide some content and setup response code. For your case you can create something that I call ExtendedJsonResult:

public class ExtendedJsonResult : JsonResult
{
    public ExtendedJsonResult(object data)
    {
        base.Data = data;
    }

    public int StatusCode { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.StatusCode = this.StatusCode;
        base.ExecuteResult(context);
    }
}

and then in controller

return new ExtendedJsonResult("Some error")
{
    StatusCode = 401,
};

You can also just return existing HttpStatusCodeResult.

NaveenBhat
  • 3,248
  • 4
  • 35
  • 48
Sławomir Rosiek
  • 4,038
  • 3
  • 25
  • 43
1

Look at this solution: ASP.NET MVC Ajax Error handling

Darin Dimitrov write very nice solutions with action filter:

public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new JsonResult
        {
            Data = new { success = false, error = filterContext.Exception.ToString() },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

Then you could write your client error handling for all status codes and use it for ajax requests.

Community
  • 1
  • 1
webdeveloper
  • 17,174
  • 3
  • 48
  • 47