2016-09-20 55 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