要在ASP.NET Core 8 Web API中使用Windows身份验证,可以按照以下步骤进行设置:
在Visual Studio中创建一个新的ASP.NET Core Web API项目。
在Startup.cs
文件中,将services.AddControllers()
修改为services.AddControllers().AddNewtonsoftJson()
,以便使用Newtonsoft.Json进行序列化。
在Startup.cs
文件的ConfigureServices
方法中,添加Windows身份验证服务:
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
Startup.cs
文件的Configure
方法中,添加身份验证中间件:app.UseAuthentication();
app.UseAuthorization();
[Authorize]
特性,以确保只有经过身份验证的用户可以访问:[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
// Controller actions...
}
User.Identity.Name
属性获取当前用户的用户名:[HttpGet]
public IActionResult Get()
{
var username = User.Identity.Name;
// Other code...
}
请注意,为了使用Windows身份验证,需要确保应用程序运行在支持Windows身份验证的环境中(如IIS)。另外,还需要确保应用程序的运行用户具有访问所需资源的权限。