2016-09-20 53 views
0

我試圖從我的Web Api返回一個401,如果用戶沒有登錄,而不是在API方法上使用Authorize屬性時將它們發送到登錄頁面。 我已經看到了一些關於如何解決這個問題的想法,但沒有人爲我工作。從窗體身份驗證應用程序的web api返回401消息

我使用web api 5.2.3,它看起來不像response.SuppressFormsAuthenticationRedirect = true; 工作了。

我也嘗試覆蓋HandleUnauthorizedRequest,沒有運氣, 它仍然將我重定向到登錄頁面。 感謝您的幫助

+0

我終於做到了,試圖回答工作又是在這裏。 http://stackoverflow.com/questions/34880817/make-web-api-authentication-return-401-instead-of-redirect-to-login-page – user973671

回答

0

通常,我使用ASP.Net核心,並且該框架對WebAPI和MVC使用相同的控制器類型。 但是,這是我怎麼會顧及這個問題,在我的啓動類的services.AddIdentity方法

config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents() 
{ 
    OnRedirectToLogin = ctx => 
    { 
     if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) 
     { 
      ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized; 
     } 
     else 
     { 
      ctx.Response.Redirect(ctx.RedirectUri); 
     } 
      return Task.FromResult(0); 
    } 
}; 

讓我知道這對你的作品

+0

是的,即時通訊不使用asp.net核心。這是一個MVC5應用程序。儘管感謝您的幫助! – user973671

相關問題