If you are adding asp.net WebApi inside asp.net MVC web site you probably want to respond unauthorized to some requests. But then ASP.NET infrastructure come into play and when you try to set response status code to HttpStatusCode.Unauthorized you will get 302 redirect to login page.
If you are using asp.net identity and owin based authentication here a code that can help to solve that issue:
public void ConfigureAuth(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider() { OnApplyRedirect = ctx => { if (!IsApiRequest(ctx.Request)) { ctx.Response.Redirect(ctx.RedirectUri); } } } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); } private static bool IsApiRequest(IOwinRequest request) { string apiPath = VirtualPathUtility.ToAbsolute("~/api/"); return request.Uri.LocalPath.StartsWith(apiPath); }
Thank you, very helpful.
ReplyDeleteAwesome.! Really very helpful. Thankx...
ReplyDeleteAwesome!!!!
ReplyDeleteThat was really helpful thanks.
ReplyDeleteI love you :)
ReplyDeleteGreat Article
ReplyDeleteASP.NET Web API Course
Web API Course
Web API Course in Chennai
ASP.NET Web API Online Course
Thanks, It helped me as well, it took me a while to find this solution.
ReplyDeleteThanks for sharing Good Information
ReplyDelete.Net Online Training Hyderabad
avast secureline vpn login, avast secureline, avast secureline vpn activation code, avast secureline tap adapter v3, avast secureline vpn virus, avas Avast Vpn Activation Code
ReplyDeleteThe writing tool that helps you produce text documents quickly and easily using mind maps. App available on macOS and Windows PCs and iPad.https://cyberspc.com/writemapper-full-crack-download/
ReplyDeleteHi.
ReplyDeleteThis writing tool is a game-changer, enabling you to effortlessly create text documents by utilizing mind maps. Available on both macOS and Windows platforms, this app streamlines the process, allowing you to produce content rapidly and with ease. Here is sharing some SnapLogic Training information may be its helpful to you.
SnapLogic Training