C# MVC登录后重定向
我有一个AccountController,用户可以在其中登录,还有一个名为Admin的区域,用户必须在其中进行自动调整才能查看。当用户使用正确的用户名和密码登录时,它会再次重定向到同一页面(C# MVC登录后重定向,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我有一个AccountController,用户可以在其中登录,还有一个名为Admin的区域,用户必须在其中进行自动调整才能查看。当用户使用正确的用户名和密码登录时,它会再次重定向到同一页面(。/Account/Login?ReturnUrl=%2FAdmin) 会计控制员 public class AccountController : Controller { [AllowAnonymous] public ActionResult Login()
。/Account/Login?ReturnUrl=%2FAdmin
)
会计控制员
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (model.Username == "User" && model.Password == "Pa$$W0rd")
{
FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
if (!string.IsNullOrWhiteSpace(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Admin", new { area = "Admin"});
}
ModelState.AddModelError("", "Brukernavn og/eller passord er feil");
}
return View();
}
}
区域管理员中的管理员控制器
[Authorize]
public class AdminController : HimmelhoytControllerBase
{
public ActionResult Index()
{
return View();
}
}
查看登录
@model Himmelhoyt.Models.AccountModels.LoginModel
@{
ViewBag.Title = "Logg inn";
}
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "form-signin" }))
{
< text>
@Html.AntiForgeryToken()
@Html.LabelFor(m => m.Username, new { @class = "sr-only" }) @Html.EditorFor(m => m.Username, new { htmlAttributes = new { @class = "form-control", placeholder = "Brukernavn", autofocus = "autofocus" } })
@Html.ValidationMessageFor(m => m.Username, "", new { @class = "bg-danger validationMessage" })
@Html.LabelFor(m => m.Password, new { @class = "sr-only" }) @Html.EditorFor(m => m.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "Passord", type = "password" } })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "bg-danger validationMessage" })
<br/>
@Html.EditorFor(x => x.RememberMe@*, new { htmlAttributes = new { @class = "checkbox" } }*@) @Html.LabelFor(m => m.RememberMe)
@Html.ValidationMessageFor(m => m.RememberMe)
<br />
@Html.Submit("Logg på", new { @class = "btn btn-lg btn-primary btn-block" })
@Html.ValidationSummary(true)
</text>
}
这行代码是你的
返回重定向到操作(“Index”,“Admin”,new{area=“Admin”})代码>
可能正在引发异常。试一试
放一个try-catch,看看有什么异常
您正在传递值,但Admin中的index方法不接受任何参数。看看这个
试试这个:
将此方法从帐户
控制器移动到管理员
控制器:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (model.Username == "User" && model.Password == "Pa$$W0rd")
{
FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
if (!string.IsNullOrWhiteSpace(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Admin", new { area = "Admin"});
}
ModelState.AddModelError("", "Brukernavn og/eller passord er feil");
}
return View();
}
并从以下位置更改视图中的控制器调用:
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "form-signin" }))
致:
然后更改移动到管理控制器的方法中的一行,从:
return View();
致:
查看它是否有效并适合您的需要如果我是正确的,我可以看到您在用户提供正确凭据但您尚未登录的情况下设置了SetAuthCookie。因此,您总是重定向到登录页面
我想你必须登录才能看到管理部分。使用您的登录方法登录
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (model.Username == "User" && model.Password == "Pa$$W0rd")
{
FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
//Sign in code should go here.
if (!string.IsNullOrWhiteSpace(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Admin", new { area = "Admin"});
}
ModelState.AddModelError("", "Brukernavn og/eller passord er feil");
}
return View();
}
您在应用程序中使用的身份验证方法是什么?它是Asp.net身份框架吗
希望这有帮助 尝试从Web.config中删除以下行
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Himmelhoyt-20140831071527.mdf;Initial Catalog=aspnet-Himmelhoyt-20140831071527;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="HimmelhoytDb" connectionString="data source=(localdb)\v11.0;initial catalog=Himmelhoyt;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<!--<authentication mode="None" />-->
<authentication mode="Forms">
<forms loginUrl="/Account/Login" />
</authentication>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<modules>
<remove name="FormsAuthentication" />
</modules>
我不知道这是否可以,但对于您的问题,我做了如下操作:
case SignInStatus.Success:
return RedirectToAction("RedirectLogin", new {ReturnUrl = returnUrl});
public ActionResult RedirectLogin(string returnUrl)
{
return User.IsInRole("Reader") ? RedirectToAction("Index", "Employees") : RedirectToLocal(returnUrl);
}
如果您不希望默认设置为“主页”或“索引”,请更改此设置:
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Dashboard", "User");
}
AccountController中的所有内容,希望对您有所帮助。问题是什么?请将您的“RedirectToAction”更改为登录后要重定向的页面。。您将“Index”和“Admin”放在那里,因此您将返回到Admin的索引:3在调试器中检查returnUrl
变量的值。如果返回重定向(returnUrl)代码>被执行,返回url是正确的(我的意思是url不等于“/Account/Login”),检查Cookie是否正确设置。@ViktorArsanov returnUrl为NULL(这也是一个问题,但稍后再处理),因此它将执行return RedirectToAction(“Index”,“Admin”,new{area=“Admin”});我是C#新手,如何检查Cookie设置是否正确?@user4034首先,检查浏览器设置。这种情况看起来Cookie没有设置。然后,我将在[HttpPost]公共操作结果登录(LoginModel model,string returnUrl)
方法中的行(ModelState.IsValid)
上设置一个断点,并在Watch debugger窗口中检查控制器用户属性。检查User.Identity.IsAuthenticated属性-该属性应等于true。不会引发异常。param说应该去一个叫Admin的地方,我想。我还尝试了返回重定向(~/Admin),因为这是我的管理索引的路径。我认为问题是没有设置验证cookies。该方法应该在我拥有它的地方工作,因为我遵循了一个它完成并工作的示例。哦,我觉得太愚蠢了。我试着做几周前在一门课上学到的事情,在他的程序中,他在FORMAT之间没有任何代码。。如果是这样的话,那就行了。Asp.net Identity framework是您推荐给初学者的吗?然后我应该看看。是的,如果您使用的是最新的技术,我指的是.net framework 4.5和Visual studio 2012、2013,我强烈建议您使用identity framework。您可以在这里找到所有必需的示例。如果您认为,是您在寻找的,请标记为答案。您可以扩展此答案,以包括您认为这将解决问题的原因的解释吗?虽然此代码片段可以解决问题,但确实有助于提高您文章的质量。请记住,您将在将来为读者回答这个问题,而这些人可能不知道您的代码建议的原因。当我删除它时,它根本就没有授权。然而,重定向是成功的。
public static string securityIsnuul(string id)
{
agancyEntities db = new agancyEntities();
if (id == null)
{
//// redirect to url??????
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Dashboard", "User");
}
public static string securityIsnuul(string id)
{
agancyEntities db = new agancyEntities();
if (id == null)
{
//// redirect to url??????
}
}