Razor 视图调用错误的操作

Razor view calls wrong action

我正在尝试在我的 Asp.Net MVC 应用程序中使用 Auth0 身份验证。我有一个名为帐户控制器的控制器,里面有两个操作:注销和登录。

我从布局视图中调用它们,如果我单击“注销”按钮,则应调用“注销”操作,如果我单击“登录”按钮,则应调用“登录”操作。问题是我点击哪个按钮并不重要,它总是执行登录操作,也许有人知道吗?

AccountController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace my_diet.Controllers
{
    public class AccountController : Controller
    {
        [Authorize]
        public async Task Logout()
        {
            await HttpContext.SignOutAsync("Auth0", new AuthenticationProperties
            {
                // Indicate here where Auth0 should redirect the user after a logout.
                // Note that the resulting absolute Uri must be whitelisted in the
                // **Allowed Logout URLs** settings for the app.
                RedirectUri = Url.Action("Index", "Home")
            });
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
        public async Task Login(string returnUrl = "/")
        {
            await HttpContext.ChallengeAsync("Auth0", new AuthenticationProperties() { RedirectUri = returnUrl });
        }

    }
}

_layouts.cshtml

<ul class="navbar-nav flex-grow-1">
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a id="qsLogoutBtn" class="nav-link text-dark" asp-controller="Account" asp-action="Logout">Logout</a>
@*@Html.ActionLink("Logout", "Logout", "Account", new object { }, new { @class = "nav-link text-dark"})*@

</li>
}
else
{
<li class="nav-item">
<a id="qsLoginBtn" class="nav-link text-dark" asp-controller="Account" asp-action="x">Login</a>
</li>
}
</ul>

试试这个。

[AllowAnonymous]
public async Task Login(string returnUrl = "/")
{
   await HttpContext.ChallengeAsync("Auth0", new AuthenticationProperties() { 
   RedirectUri = returnUrl });
}

更多规格:

您还可以使用 AllowAnonymous 属性允许未经身份验证的用户访问个人操作。

例如:

[Authorize]

    public class AccountController : Controller
    {
        [AllowAnonymous]
        public ActionResult Login()
        {
        }

        public ActionResult Logout()
        {
        }
    }

这将仅允许经过身份验证的用户访问AccountController登录操作除外 ,每个人都可以访问,无论他们的身份是经过身份验证还是未经身份验证/匿名。

警告:

[AllowAnonymous] 绕过所有授权语句。如果将 [AllowAnonymous] 和任何 [Authorize] 属性结合使用,则 [Authorize] 属性将被忽略。例如,如果您在控制器级别应用 [AllowAnonymous],则同一控制器(或其中的任何操作)上的任何 [Authorize] 属性都将被忽略。