早些时候我遇到了类似的问题。
我创建了asp mvc 默认模板项目并在home控制器上设置了authorization
属性。
当我运行app url时:
http://localhost:48403/Account/LogOn?ReturnUrl=%2f
当用户未经过身份验证时,我尝试获得的只是http://localhost:48403
,但我对重新安装设置没有运气:(
我试图把它放在global.asax
中,但没有运气:
routes.MapRoute("Login", "",
new { controller = "Account", action = "LogOn" }
);
这是我的全部global.asax
routes.MapRoute("About", "About",
new { controller = "Home", action = "About" }
);
routes.MapRoute("Login", "",
new { controller = "Account", action = "LogOn" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
答案 0 :(得分:2)
你可以编写一个自定义的Authorize属性,相反,如果重定向将直接呈现LogOn视图:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var viewResult = new ViewResult
{
ViewName = "~/Views/Account/LogOn.cshtml"
};
filterContext.Result = viewResult;
}
}
然后用它装饰你的HomeController:
[MyAuthorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
然后你的AccountController不再需要担心ReturnUrls:
public class AccountController : Controller
{
[HttpPost]
public ActionResult LogOn(LogOnModel model)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
// TODO: obviously here instead of hardcoding the country and the city
// you might want to retrieve them from your backend given the username
return RedirectToAction("Index", "Home", new { country = "uk", city = "london" });
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
return View(model);
}
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
}
最后你需要在〜/ Views / Account / LogOn.cshtml中修改表单的动作以指向正确的控制器:
@using (Html.BeginForm("LogOn", "Account")) {
...
}
您可以默认离开路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}