嗨,经过互联网上发现的几乎所有教程后,我仍然无法解决我的问题,看来尽管我的控制器上有授权标签,它仍然允许每个请求,即使他们没有登录。
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());
}
GLOBAL 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
);
}
我错过了什么吗?
答案 0 :(得分:0)
不,你的代码似乎是对的。甚至Home控制器上的Authorize属性也是多余的,因为您已经在RegisterGlobalFilters方法中为所有控制器全局注册了它。
AccountService.login方法有效吗?也许它总是回归真实。
答案 1 :(得分:0)
检查会话cookie是否已创建:
还尝试返回您用于登录的用户名。使用下面的代码或只是使用调试器查看此值。
[Authorize]
public ActionResult Test()
{
return Content(HttpContext.Current.User.Identity.Name);
}
答案 2 :(得分:0)
检查Global.asax.cs是否缺少这些类型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;