Razor视图调用了错误的操作

问题描述 投票:0回答:1

我正在我的Asp.Net MVC应用程序中尝试使用Auth0身份验证。我有一个叫做Account controller的Controller,里面有两个动作:Logout和Login。

我从布局视图中调用它们,如果单击“注销”按钮,则应调用“注销”操作,如果单击“登录”按钮,则应调用“登录”操作。问题是我单击哪个按钮都没有关系,它总是执行“登录”操作,也许有人有什么主意?

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>
asp.net-mvc authentication android-asynctask auth0 razor-pages
1个回答
1
投票

尝试一下。

[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]属性。

© www.soinside.com 2019 - 2024. All rights reserved.