当Windows和匿名身份验证都设置为启用时,我试图使Asp.net核心Web API 2.1与IIS一起使用。当我关闭匿名功能但未设置匿名功能时,该API的效果很好。
我已在IIS上同时启用Windows和Anonymous。
_logger.LogInformation("Entered into windows Authentication");
services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme);
services.AddMvcCore(opts =>
{
}).SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1)
.AddFormatterMappings()
.AddDataAnnotations() // Optional if no validation using attributes
.AddCors() //
.AddApiExplorer() // Not Optional
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
})
.AddJsonFormatters(o =>
{
o.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
o.Formatting = Newtonsoft.Json.Formatting.Indented;
});
在我的startup.cs中,Configure方法如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseCors();
app.UseAuthentication();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ctrac API");
});
}
以及在我的控制器上
[HttpGet, AutoQueryable]
[Authorize]
public IQueryable<DocumentViewModel> Get([FromServices] IQueryableRepository repository, [FromServices] IHttpContextAccessor context)
{
_logger.LogInformation($"This is httpContext userid: {context?.HttpContext?.User?.Identity?.Name}"); //This is null
return repository.GetIQueryable<DocumentView>().Where(x => x.ActiveFlag == "Y"
&& _userRepo.User.DocTypes.Contains(x.DocumentTypeCode))
.OrderBy(a => a.DocTypeCategory).ThenBy(a => a.SubCategory).ThenByDescending(a => a.Id).UseAsDataSource(_mapper).For<DocumentViewModel>();
}
context?.HttpContext?.User?.Identity?.Name我希望这样做会产生一些结果,因为该方法中包含Authorize Annotation。