MVC 5重定向到登录页面不使用OWIN

Jef*_*eff 7 c# owin asp.net-mvc-5

我正试着用OWIN来解决问题.我创建了两个MVC 5项目.一个使用Aspnet.Identity进行身份验证,另一个使用另一个空项目.

我在emptyp项目中添加了以下内容:

  • 具有登录操作和相应视图的帐户控制器

  • Startup.cs和另一个部分Startup.cs

public partial class Startup
{
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

我在Home控制器中使用两个项目中的[Authorize]属性修饰了About操作.

当我运行第一个项目并在登录前转到"关于"屏幕时,它会按预期重定向到登录操作.当我为第二个项目做同样的事情时,我得到一个"HTTP错误401.0 - 未经授权"而不是重定向.

知道什么会导致第二个这样做吗?

Vli*_*nce 8

我创建了两个新的类似项目,并能够重现您的错误.

在空白项目中,我必须安装Microsoft.Owin.Host.SystemWeb(通过Nuget),一旦我这样做,我在Startup.cs类中遇到了一堆错误.结束了这个:

[assembly: OwinStartupAttribute(typeof(v2.Startup))]
namespace v2
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }

        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,当我调用用[Authorize]属性修饰的About()方法时,我现在能够访问/查看我的Login视图.

希望这可以帮助!文斯

  • 感谢您花时间尝试这个.我再次开始清洁,最终能够找到两个不同的问题.在我尝试这个项目的一个项目中,我在CookieAuthenticationOptions中有"AuthenticationMode = AuthenticationMode.Passive".这是我正在尝试的其他东西遗留下来的.在另一个项目中,我忘了从Startup.Configuration()调用Startup.ConfigureAuth()!所以基本上是两个粗心的错误.我回到正轨并试图找出下一个问题.... (2认同)

Aar*_*man 8

每个ASP.NET MVC 5 Web.config:"FormsAuthenticationModule"或"FormsAuthentication"

<system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

为了额外的安全性我留下了"错字"处理程序(如果微软稍后更改它给我)

<system.webServer>
    <modules>
     <remove name="FormsAuthenticationModule" />
     <remove name="FormsAuthentication" />
    </modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)