services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "YourIssuer",
ValidAudience = "YourAudience",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey"))
};
});
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
public ActionResult Get()
{
return "Hello World!";
}
}
app.UseExceptionHandler(errorApp =>
{
errorApp.Use(async (context, next) =>
{
var error = context.Features.Get();
if (error != null && error.Error != null)
{
// 以调试输出的方式记录错误信息
Debug.WriteLine(error.Error);
}
await next();
});
});
注意:在生产环境中,应避免暴露详细的错误信息。