I have a part of my site that has a lightweight xml / json REST API. Most of my site is behind auth forms, but authentication is required to complete some of my API actions.
I have my own AuthorizeAttribute attribute for my API, which I use to check for specific permissions, and when it fails, it leads to error 401. Everything is fine, except that I use auth forms, Asp.net conveniently converts this to 302 redirects to my login page.
I saw some previous questions that seem a bit hacky to either return 403 or put some logic in global.asax protected void Application_EndRequest () which will essentially convert 302 to 401, where it meets any criteria.
- Previous question
- Previous Question 2
What I'm doing right now seems like one of the questions, but instead of checking Application_EndRequest () for 302, I return my authorize attribute 666 which tells me that I need to set this to 401.
Here is my code:
protected void Application_EndRequest() { if (Context.Response.StatusCode == MyAuthAttribute.AUTHORIZATION_FAILED_STATUS) {
Even if this works, my question is there is something in Asp.net MVC 2, what would prevent me from doing this? Or, in general, is there a better way? I would think that it would be very useful for those who make REST api or just people who execute ajax requests in their controllers. The last thing you want is to make a request and get the contents of the login page, not json.
rest asp.net-mvc asp.net-mvc-2
Greg roberts
source share