在Login方法中调用Unauthorized方法时出现编译错误:当前上下文无该名称
问题原因
你的BaseApiController没有继承ASP.NET Core Web API控制器的核心基类ControllerBase,而Unauthorized是ControllerBase提供的内置辅助方法,因此子类AccountController无法访问该方法。
解决方案
修改BaseApiController,让它继承ControllerBase即可:
using Microsoft.AspNetCore.Mvc; namespace API.Controllers { [ApiController] [Route("api/[controller]")] public class BaseApiController : ControllerBase { } }
补充说明
ControllerBase包含了Web API控制器常用的Action结果辅助方法,比如Ok()、NotFound()、BadRequest()等,继承它之后,所有基于BaseApiController的控制器都能直接使用这些方法,这是ASP.NET Core Web API开发的标准做法。
如果暂时不想修改基类,也可以手动返回Unauthorized结果,示例:
// 替代 return Unauthorized("invalid username"); return new UnauthorizedObjectResult("invalid username"); // 替代 return Unauthorized(); return new UnauthorizedResult();
内容的提问来源于stack exchange,提问作者Юрій Луценко
相关产品推荐
相关产品推荐

