簡體   English   中英

登錄后MVC重定向

[英]MVC Redirect after login

我有一個 AccountController,用戶可以在其中登錄,還有一個名為 Admin 的區域,用戶必須在其中自動查看。 當用戶使用正確的用戶名和密碼登錄時,它會再次重定向到同一頁面 ( ../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();
        }
}

區域 Admin 中的 AdminController

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

在 Account-controller 中, return RedirectToAction("Index", "Admin", new { area = "Admin" }); 被執行,但正如我所說,它只重定向到同一頁面。

已編輯的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>

嘗試從您的 Web.config 中刪除以下幾行

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

嘗試這個:

將此方法從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();
    }

並將視圖中的控制器調用更改為:

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

到:

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

然后在您移動到 ​​Admin Controller 的方法中更改一行,從:

return View();

到:

return Redirect("Index");

看看它是否有效並適合您的需求

如果我是正確的,如果用戶提供正確的憑據但您尚未登錄,我可以看到您設置了 SetAuthCookie。 因此,您總是重定向到登錄頁面。

我認為您必須登錄才能看到管理部分。 使用您的 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();
    }

您在應用程序中使用的身份驗證方法是什么? 是 Asp.net Identity 框架嗎?

希望這可以幫助。

我不知道這是否可以,但是對於您的問題,我執行了以下操作:

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 中的所有內容,希望對您有所幫助。

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

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

你這行代碼return RedirectToAction("Index", "Admin", new { area = "Admin"});

可能會拋出異常。 嘗試

  1. 放一個 try catch 看看有什么異常。
  2. 您正在傳遞 value ,但您在 Admin 中的 index 方法不接受任何參數。 檢查這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM