在我的賬戶控制器,在登錄操作,有下面的代碼:MVC5(Asp.Net4.5.2) - RedirectToAction在一種情況下一點兒也不回
case "Sucess":
string rule = CheckRule(model.username, model.Password);
Response.SetCookie(SetAuthCookie(model.username, model.RememberMe, rule));
return RedirectToAction("Index", rule);
在checkrule,我返回字符串的名字另一個控制器,其中有管理員和BasicUser,這裏是這些代碼:
{
[Authorize]
public class AdminController : Controller
{
private bool attAuthor = isAuthorized();
private bool attAuth = isAuthenticated();
private string rule = returnrule();
// GET: Admin
public ActionResult Index()
{
if (!attAuthor)
{
return RedirectToAction("erro401",rule);
}
else
{
return View();
}
}
public ActionResult erro401()
{
return View("erro401");
}
}
和:
{
[Authorize]
public class BasicUserController : Controller
{
private bool attAuthor = isAuthorized();
private bool attAuth = isAuthenticated();
private string rule = returnrule();
// GET: BasicUser
public ActionResult Index()
{
if (!attAuthor)
{
return RedirectToAction("erro401", rule);
}
else
{
FormsAuthenticationTicket authticket = get_ticket();
string str = rule + "/" + authticket.Name;
ViewBag.Htmlstr = str;
return View();
}
}
public ActionResult erro401()
{
return View("erro401");
}
}
}
在RouteConfig:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "BasicUser",
url: "{controller}/{action}/{id}",
defaults: new { controller = "BasicUser", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Admin",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
);
如果我和它完美的管理員用戶登錄,但有一個基本的用戶navagador不重定向到的路線,簡單地說就是登錄屏幕上,如果我輸入控制器地址的作品。 我添加了一個標籤html來查看cookie userdata,這工作正常(顯示的BasicUserRule)。
很抱歉,如果我的問題不是很清楚,我是新手...
塞達特您好,感謝的答案,我會解決這些路線,但'HttpStatusCode.Unauthorized',在那裏我可以配置此帳戶登錄自動響應?我把登錄URL放在Web.config上的FormsAuthentication中:'
@RogérioFerreira應該足夠了。這是默認行爲。如果您想在操作前強制登錄,您還可以使用'[Authorize]'屬性(而不是處理HTTP結果)。 –
謝謝,我已經做到了。 –