我目前正在将 WebForms/MVP 应用程序的一些组件迁移到 MVC 中。到目前为止,除了授权之外,一切正常。无论如何,当我导航到 MVC 版本的登录页面时,我会被重定向到在Web.config
:
<authentication mode="Forms">
<forms name=".MyWebSite" enableCrossAppRedirects="true" loginUrl="Login.aspx" timeout="60" path="/" defaultUrl="~/Pages/Landing.aspx"></forms>
</authentication>
我尝试过使用AllowAnonymous
但似乎 webforms 配置优先。这是我的登录控制器:
[RouteArea("User", AreaPrefix = "")]
public class AuthenticationController : Controller {
[Route("Login")]
[AllowAnonymous]
public ActionResult Login() {
return View();
}
}
我的目录结构如下所示:
> Web Project
> Areas
> User
> Controllers
> AuthController
> Views
> Login.cshtml
在我的 web.config 中,我看到以下内容允许匿名访问错误页面:
<location path="Error">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
然而,复制这个Areas
路径不起作用(大概是因为 cshtml 文件实际上并不像 aspx 页面那样位于那里?)。
现在,如果我登录(通过 aspx 版本的登录)并且我的用户已通过身份验证,我就可以很好地访问 MVC 实现。路由和渲染工作得非常好。它只是允许未经身份验证的用户访问 MVC 页面(不重定向到 aspx 实现),这似乎是一个挑战。我究竟做错了什么?
EDIT我发现了一个非常hacky的部分解决方案(基于关闭一个子目录的 ASP.Net WebForms 身份验证)如下:
protected void Application_BeginRequest(object sender, EventArgs e) {
// lots of existing web.config controls for which webforms folders can be accessed
// read the config and skip checks for pages that authorise anon users by having
// <allow users="?" /> as the top rule.
// https://stackoverflow.com/questions/4616524/turning-off-asp-net-webforms-authentication-for-one-sub-directory
// check local config
var localAuthSection = ConfigurationManager.GetSection("system.web/authorization") as AuthorizationSection;
// this assumes that the first rule will be <allow users="?" />
var localRule = localAuthSection.Rules[0];
if (localRule.Action == AuthorizationRuleAction.Allow && localRule.Users.Contains("?")) {
// then skip the rest
return;
}
// get the web.config and check locations
var conf = WebConfigurationManager.OpenWebConfiguration("~");
foreach (ConfigurationLocation loc in conf.Locations) {
// find whether we're in a location with overridden config
// get page name
var currentPath = Path.GetFileName(this.Request.Path);
if (currentPath.Equals(loc.Path, StringComparison.OrdinalIgnoreCase)) {
// get the location's config
var locConf = loc.OpenConfiguration();
var authSection = locConf.GetSection("system.web/authorization") as AuthorizationSection;
if (authSection != null) {
// this assumes that the first rule will be <allow users="?" />
var rule = authSection.Rules[0];
if (rule.Action == AuthorizationRuleAction.Allow && rule.Users.Contains("?")) {
// then skip the rest
return;
}
}
}
}
}
这意味着我可以像这样指定“登录”:
<location path="Login">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
但是,除非我仔细检查并为这些文件类型添加规则,否则所有关联的 CSS/JS 都不会被渲染。有got对此进行更优雅的修复。