亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

ASP.NET Core 3 API 忽略帶有 Bearertoken 的授權屬性

ASP.NET Core 3 API 忽略帶有 Bearertoken 的授權屬性

C#
心有法竹 2022-12-24 10:06:39
我正在研究 ASP.NET Core Web API。我使用的是最新版本 3.0.0-preview4.19216.2。我有問題,我的 API-Controller 忽略了 Authorize-Attribute 但在另一個控制器上 Attribute 工作正常。    [Route("api/[controller]")]    [ApiController]    [Authorize(AuthenticationSchemes =JwtBearerDefaults.AuthenticationScheme)]    public class SuppliersController : ControllerBase    {        [HttpGet("GetAll")]        public IActionResult GetAll()        {            var companyId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value); // throws nullreference exception            return Ok();        }    }但是在另一個控制器上我有類似的東西但是屬性按預期工作    [Route("api/[controller]")]    [ApiController]    [Authorize]    public class UsersController : ControllerBase    {        [HttpGet("{id}")]        public IActionResult GetById(int id)        {            var test = User.Claims.FirstOrDefault(c => c.Type == "Company_Id").Value;        }    }在用戶控制器中一切正常。我也在沒有的 SupplierController 中嘗試過認證方案但沒有什么不同。
查看完整描述

1 回答

?
UYOU

TA貢獻1878條經驗 獲得超4個贊

好的,我在這篇博文.NET Core 3.0 Preview 4 中的 ASP.NET Core 更新中找到了答案

我必須更改我的身份驗證注冊順序

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {


        app.UseHttpsRedirection();

        app.UseAuthorization();

        app.UseAuthentication();


        app.UseRouting();

        app.UseEndpoints(routes =>

        {

            routes.MapControllers();

        });

    }


 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

    {


        app.UseRouting();


        app.UseHttpsRedirection();

        app.UseAuthentication();

        app.UseAuthorization();


        app.UseEndpoints(routes =>

        {

            routes.MapControllers();

        });

    }

所以這解決了我的問題。


查看完整回答
反對 回復 2022-12-24
  • 1 回答
  • 0 關注
  • 97 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號