I have an existing ASP.NET Webforms / MVC application (it uses a mixture of technologies), to which I want to add a Web API to use for external ajax API calls (to replace older web services and WCF).
The existing ASP.NET WebForms application uses forms authentication, so if a login fails, it will redirect to a Webforms login page. I do NOT not want this for the Web API, I always just want to return json data (not a bunch of HTML).
To disable the login form, I found I could add the following toGlobal.asax:
protectedvoidApplication_BeginRequest(Objectsender,EventArgse) { stringtestPath=$"{Context.Request.ApplicationPath.ToLowerInvariant()}/{BaseConstants.WebApiRoutePrefix}/"; boolisWebApiRequest=Context.Request.Path.ToLower().Contains(testPath); if(isWebApiRequest&&FormsAuthentication.IsEnabled&&!Context.Request.IsAuthenticated) { Context.Response.SuppressFormsAuthenticationRedirect=true;<----thisdisablestheloginpage } }
The above does stop the login page, but I then noticed the Web API calls could go through with no authentication at all.
So I created an authorization attribute to use for the Web API controllers:
publicclassWebApiAuthorizationAttribute:System.Web.Http.AuthorizeAttribute { publicoverridevoidOnAuthorization(HttpActionContextactionContext) { .. //ifnotauthreturnsaHttpStatusCode.Unauthorized, } }
This code (almost) all works fine, however, just before I get the response for my Ajax call (in my case from an Angular app), I always get a browser login dialog...
If I click cancel, I then get the response back in the Angular application with the JSON etc I am after.
Can I stop the dialog from displaying, so I just get back any error JSON?
Thanks in advance