Search code examples
c#asp.net-mvcajax.beginformjsonresult

What is the right approach for send a failure to Ajax.BeginForm?


I'm starting using Ajax.BeginForm and I understood that I can call an Action of a controller and get its response. So, if the user is trying to login, I've created a CheckLogin Action, which expects the username and password of the user. If the login and password are right, I return a Json with redirect Uri to my call and everything went fine, but I don't know how a failure should work. Should I throw an exception? Should I return a bad request?

return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, "Invalid credentials");

Which one is the right approach?

Thanks in advance guys!


Solution

  • It depends on the type of failure...if the credentials are invalid then you should return a suitable HTTP status, maybe "Bad Request" (400), or maybe "Forbidden" (403), depending how you want it to work.

    If the code actually crashes then it would cause an exception...and that would result in a HTTP Internal Server Error (500) status. This indicates a very different scenario to the client. You should only use that if an unexpected error occurs.

    An anticipated problem, such as an invalid password, should result in a different status being returned which gives the client an indication of the nature of the issue. Bad Request is probably the right status for that, but different people have different opinions on it. There's no hard and fast rule, only guidance.