简体   繁体   English

登录后MVC重定向

[英]MVC Redirect after login

I have an AccountController where users can login, and an area named Admin where users have to been autorized to see.我有一个 AccountController,用户可以在其中登录,还有一个名为 Admin 的区域,用户必须在其中自动查看。 When users log in with correct username and pw, it redirects to the same page again ( ../Account/Login?ReturnUrl=%2FAdmin )当用户使用正确的用户名和密码登录时,它会再次重定向到同一页面 ( ../Account/Login?ReturnUrl=%2FAdmin )

AccountController帐户控制器

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();
        }
}

AdminController in area Admin区域 Admin 中的 AdminController

[Authorize]
public class AdminController : HimmelhoytControllerBase
{
        public ActionResult Index()
        {
            return View();
        }
}

View Login查看登录

@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>
    }

In the Account-controller, return RedirectToAction("Index", "Admin", new { area = "Admin" });在 Account-controller 中, return RedirectToAction("Index", "Admin", new { area = "Admin" }); is executed, but as I said, it only redirects to the same page.被执行,但正如我所说,它只重定向到同一页面。

EDITED Web.config已编辑的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>

Try to remove the following lines from your Web.config尝试从您的 Web.config 中删除以下几行

<modules>
  <remove name="FormsAuthentication" />
</modules>

Try this:尝试这个:

move this method from the Account controller to the Admin controller:将此方法从Account控制器移动到Admin控制器:

    [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();
    }

And change the controller call in your View from:并将视图中的控制器调用更改为:

@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "form-signin" }))

to:到:

@using (Html.BeginForm("Login", "Admin", FormMethod.Post, new { @class = "form-signin" }))

Then change a line in the method you moved to the Admin Controller, from:然后在您移动到 ​​Admin Controller 的方法中更改一行,从:

return View();

to:到:

return Redirect("Index");

See if it works and suits your needs看看它是否有效并适合您的需求

If I am correct, I can see that you set SetAuthCookie if the user provide correct credentials but you haven't sign in yet.如果我是正确的,如果用户提供正确的凭据但您尚未登录,我可以看到您设置了 SetAuthCookie。 because of that you always redirected to the login page.因此,您总是重定向到登录页面。

I think you have to sign in in order to see the admin section.我认为您必须登录才能看到管理部分。 Use your sing in methods to sign in.使用您的 sing in 方法登录。

[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();
    }

What is the authentication method you used in your application?您在应用程序中使用的身份验证方法是什么? Is it Asp.net Identity framework?是 Asp.net Identity 框架吗?

Hope this helps.希望这可以帮助。

I do not know if this is okay but for your problem I did as follows:我不知道这是否可以,但是对于您的问题,我执行了以下操作:

case SignInStatus.Success:
return RedirectToAction("RedirectLogin", new {ReturnUrl = returnUrl});

public ActionResult RedirectLogin(string returnUrl)
{
   return User.IsInRole("Reader") ? RedirectToAction("Index", "Employees") : RedirectToLocal(returnUrl);
}

And if you do not want it to be "Home" or "Index" as default, change this:如果您不希望它默认为“主页”或“索引”,请更改以下内容:

private ActionResult RedirectToLocal(string returnUrl)
{
  if (Url.IsLocalUrl(returnUrl))
  {
     return Redirect(returnUrl);
  }
     return RedirectToAction("Dashboard", "User");
 }

Everything in your AccountController, hope it helps.您 AccountController 中的所有内容,希望对您有所帮助。

public static string securityIsnuul(string id)
{
    agancyEntities db = new agancyEntities();

    if (id == null)
    {
      //// redirect to url??????
    }       
}

Your this line of code return RedirectToAction("Index", "Admin", new { area = "Admin"});你这行代码return RedirectToAction("Index", "Admin", new { area = "Admin"});

might be throwing exception.可能会抛出异常。 Try尝试

  1. putting a try catch and see what is the exception.放一个 try catch 看看有什么异常。
  2. You are passing value , but your index method in Admin does not take any param.您正在传递 value ,但您在 Admin 中的 index 方法不接受任何参数。 Check this.检查这个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM