在ASP.NET核心登录

时间:2017-06-10 22:27:19

标签: c# asp.net authentication asp.net-core-mvc

我有个人帐户的ASP.NET核心应用程序;与VS2017生成的内容非常相似。出于测试目的,我将[Authorize]属性放在Home控制器中的About()操作上。我按预期重定向到“登录”页面,我看到该网址为http://localhost:5000/Account/Login?ReturnUrl=%2FHome%2FAbout - 也正如预期的那样。但是,在POST登录方法中,ReturnUrl为null。我在帐户控制器中有登录方法:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model) {
...
}

我还明确地尝试ReturnUrl作为参数,有或没有[FromQuery]。在所有排列中它都是空的。

3 个答案:

答案 0 :(得分:1)

您应该确定使用

Html.BeginForm("Login", "Account", new {ReturnUrl = Request.QueryString["ReturnUrl"] })


[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginInputModel model, string ReturnUrl) {
...
}

答案 1 :(得分:1)

对于 .net core,这是解决问题的方法。

在您的视图中,

@using (Html.BeginForm(new { returnUrl = Context.Request.Query["ReturnUrl"] }))

在您的控制器中,

[HttpPost]
public IActionResult Login(YourViewModel m, string returnUrl = null)
{
 if (!string.IsNullOrEmpty(returnUrl))
 {
  return LocalRedirect(returnUrl);
 }
 return RedirectToAction("Index", "Home");
}

答案 2 :(得分:0)

这就是我设法让我的工作

采取行动

        [HttpGet]
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                if (Url.IsLocalUrl(ViewBag.ReturnUrl))
                    return Redirect(ViewBag.ReturnUrl);

                return RedirectToAction("Index", "Home");
            }

            return View();
        }

我的表单是这样的:

  <form asp-action="Login" method="post" asp-route-returnurl="@ViewBag.ReturnUrl" >

发布操作:

[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> Login(VMLogin model, string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;

    if (!ModelState.IsValid)
    {
        return View(model);
    }

     //Authentication here 
  
    if (Url.IsLocalUrl(ViewBag.ReturnUrl))
        return Redirect(ViewBag.ReturnUrl);

 
    return RedirectToAction("Index", "Home");
}