Jezz Santos - 225 - Sep 25, 2014

MVC + ServiceStack + angularjs

My MVC web site serves various ASP.NET MVC pages using controllers etc. just like a normal MVC site, and it is also configured with custom error pages (i.e. for 401. 404, 500), but HandleErrorAttribute is removed.

From my angularjs app I am calling SS services on the same site (in the /api) location.

Unfortunately, for some reason, that I just cannot work out, when my SS service throws an HttpException for a 401, ASP.NET is redirecting the angular client to a login page that does not exist in my site. This is useful behavior for the MVC app (even though I cant figure out what is doing it for me). BUT the angular client cannot handle this 302 redirect. It just wants to get the 401 without any redirect.

I found this reference: from Wayne https://github.com/ServiceStack/ServiceStack/commit/0f1543562893865ca1c81c1898f6aeb85f929521

But cant get that configured to work on my site (in web.config).

Besides which, the Request.IsAjaxRequest thing does not seem to work for angular clients.

I know this is an age-old problem, can someone give me guidance on how to fix it?

Can you post the HTTP Request + Response headers that’s showing the redirect using WebInspector.

Jezz Santos:

K, have learned some more. 1) angular no longer sends the necessary ajax headers (X-Requested- With=XMLHTTPREQUEST) in its requests (they removed it as an optimization - must be some anti-microsoft customer sentiment), so that Request.IsAjaxRequest cannot work. 2) it seems that the Mvc.AuthorizeAttribute might be the mechanism that is doing the actual redirecting to login page with a 302. I definatley have that attribute in use in my MVC app.

I can work around the first issue by implmenting my own IsApiRequest (instead of IsAjaxRequest) by looking at the Request path. In other words, if the request is for a service api hosted at /api, then I must should not redirect.

Now I need to decode what Mvc.AuthorizeAttribute does to do the redirect and stop/workaround that happening for calls to /api.

Jezz Santos:

Update: just found the mechanism that is doing the actual redirect to login page /Account/Login. It is not the AthorizeAttribute at all as I thought. Its down to a piece of code in: App_Start.Auth => ConfigureAuth, that does the actual redirect.
I found the correct path forward from this great article: http://www.codeproject.com/Articles/806029/Getting-started-with-AngularJS-and-ASP-NET-MVC-Par, and fortunately for me more knowledge on how to handle 401’s in general from an angular app.

I am good from here. thanks

ok brilliant, glad its sorted.