Asp.net core webapi 当点击控制器而不是内容时,授权API返回HTML

Asp.net core webapi 当点击控制器而不是内容时,授权API返回HTML,asp.net-core-webapi,identityserver4,Asp.net Core Webapi,Identityserver4,我在identity server项目中有一个非常基本的web API控制器: namespace Project.IDP.Controllers { [Route("api/[controller]")] [ApiController] public class MyController : ControllerBase { [HttpGet] public IActionResult Test()

我在identity server项目中有一个非常基本的web API控制器:

namespace Project.IDP.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MyController : ControllerBase
    {
        [HttpGet]
        public IActionResult Test()
        {
            return Ok("Test");
        }
    }
}
如果我通过邮递员给这个控制器打电话,我会收到一个OK回复200和内容“Test”,很好

但是,如果我添加Authorize属性,我会收到HTML!HTML是Identity Server的登录页面。但是,我已经授权并且正在请求中传递访问令牌(全部通过邮递员)

我的客户端设置如下:

    new ApiResource[]
    {
        new ApiResource(IdentityServerConstants.LocalApi.ScopeName),
        new ApiResource("myapi", "My API" )
        {
            Scopes = new List<Scope>
            {
                new Scope("myapi.mi_test", "MI Access")
            }
        }
    };
新客户 { ClientId=“m2m”, ClientName=“机器2机器客户端”, AllowedGrantTypes=GrantTypes.ClientCredentials, 客户秘密= { 新密码(“Secret.Sha256()) }, 允许范围={ IdentityServerConstants.LocalApi.ScopeName, “myapi.mi_测试” } },

API如下所示:

    new ApiResource[]
    {
        new ApiResource(IdentityServerConstants.LocalApi.ScopeName),
        new ApiResource("myapi", "My API" )
        {
            Scopes = new List<Scope>
            {
                new Scope("myapi.mi_test", "MI Access")
            }
        }
    };


但是我无法让它工作,我缺少什么?

我有一个类似的设置,唯一的区别是您需要在Authorize属性中指定特定的身份验证策略。在“MyController”中,将授权属性更改为:

[Authorize(LocalApi.PolicyName)]
此要求在IdenityServer文档中显示,网址为:


如果您需要帮助,恐怕您必须显示webapi站点的启动文件。谢谢@Bryan Lewis。这是可行的,但我确实有一个。。。我想更进一步,拥有一个自定义策略,然后将Authorize属性用于该策略。一旦我这样做了,我就遇到了同样的问题,html就会返回。如果你想再帮我一次忙,我会再发一个问题…@Sun,看来有人已经为我们回答了这个问题啊,让我试一试,效果不错。再次感谢你的帮助。
    services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "https://localhost:31101";
                options.ApiName = "myapi";
            });
[Authorize(LocalApi.PolicyName)]