嗨,在几乎耗尽了互联网上找到的所有教程后,我仍然无法解决我的问题,似乎尽管我的控制器上有authorize标签,但它仍然允许每个请求,即使它们没有登录。
WebConfig
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>家庭控制器
[Authorize]
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}登录
public ActionResult Login()
{
InitializeDropdown();
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
//selects model state errors if any
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
//AccountService accountService = new AccountService();
bool loginsuccess = AccountService.login(model.UserName, model.Password, model.Domain);
if (loginsuccess == false)
{
ModelState.AddModelError("", Session["Error"].ToString());
}
else
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
//FormsAuthentication.RedirectFromLoginPage(model.UserName, false);
}
}
return View(model);
}RegisterGlobalFilters
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
}全局ASAX
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//AuthConfig.RegisterAuth();
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}我错过什么了吗?
发布于 2014-09-11 15:54:32
不,您的代码似乎是正确的。即使是主控制器上的Authorize属性也是多余的,因为您已经在RegisterGlobalFilters方法中为所有控制器全局注册了它。
AccountService.login方法有效吗?也许它返回的总是真的。
发布于 2014-09-11 16:06:56
检查是否创建了会话cookie:

还要尝试返回您用来登录的用户名。使用下面的代码,或者只需使用调试器查看此值。
[Authorize]
public ActionResult Test()
{
return Content(HttpContext.Current.User.Identity.Name);
}发布于 2015-09-25 10:32:27
检查Global.asax.cs是否缺少以下类型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;https://stackoverflow.com/questions/25781543
复制相似问题