[英].Net Core 2.0 REST API w/ Windows Auth - Preflight responding with 401 Unauthorized
我正在使用.NET Core 2.0和Angular 4在本地創建網頁。 我可以讓前端成功提交GET請求,但不能提交POST。 我已經嘗試了各種方式來啟用CORS和Windows身份驗證,但是我總是收到未授權的錯誤。 我想在飛機前錯過什么? 我假設它與Windows身份驗證有關,但是我發現的所有內容都只是說我需要'withCredentials:true'標頭選項。
角度服務
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
withCredentials: true
};
@Injectable()
export class TestService {
constructor(private http: HttpClient) { }
private baseURL = 'http://localhost:58214/api/{insert_app_name_here}';
getAllRules() {
console.log('Getting rules');
return this.http.get<RuleItem>(this.baseURL).subscribe(res => {
console.log(res);
});
}
createNewRule(ri: RuleItem) {
return this.http.post<RuleItem>(this.baseURL, JSON.stringify(ri), httpOptions).subscribe(res => {
console.log(res);
}, err => {
console.log('Error occurred: ', err);
});
}
}
.NET CORE 2.0控制器
// [EnableCors("SitePolicy")]
[Route("api/[controller]")]
public class TestController : Controller
{
private readonly RuleContext _context;
public TestController(RuleContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<RuleItem> GetAll()
{
return _context.RuleItems.ToList();
}
[HttpGet("{id}", Name = "GetRule")]
public IActionResult GetById(long id)
{
var item = _context.RuleItems.FirstOrDefault(r => r.Id == id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
[HttpPost]
public IActionResult Create(RuleItem item)
{
if (item == null)
{
return BadRequest();
}
_context.RuleItems.Add(item);
_context.SaveChanges();
return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
}
啟動文件
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
/*
services.AddCors(options =>
{
options.AddPolicy("SitePolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials();
});
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);*/
services.AddMvc();
var connection = @"Server=servername;Database=dbname;Trusted_Connection=true;MultipleActiveResultSets=True;";
services.AddDbContext<RuleContext>(options => options.UseSqlServer(connection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// app.UseCors("SitePolicy");
app.UseMvc();
}
}
web.config不確定是否可以通過編程方式添加CORS,是否需要此功能,但這是成功擺脫“不存在允許的頭信息”錯誤的唯一解決方案
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
編輯 -進行了以下更改:刪除了web.config文件,添加了全局CORS規則。 更改如下:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
//services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc();
var connection = @"Server=server;Database=db;Trusted_Connection=true;MultipleActiveResultSets=True;";
services.AddDbContext<RuleContext>(options => options.UseSqlServer(connection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowCredentials();
});
app.UseMvc();
}
}
控制者
[Route("api/[controller]")]
public class TestController : Controller
{
private readonly RuleContext _context;
public TestController(RuleContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<RuleItem> GetAll()
{
return _context.RuleItems.ToList();
}
[HttpGet("{id}", Name = "GetRule")]
public IActionResult GetById(long id)
{
var item = _context.RuleItems.FirstOrDefault(r => r.Id == id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
[HttpPost]
public IActionResult Create(RuleItem item)
{
if (item == null)
{
return BadRequest();
}
_context.RuleItems.Add(item);
_context.SaveChanges();
return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
}
這是我現在收到的錯誤消息的圖像: 401錯誤
問題最終在於傳遞Windows令牌。 在預檢請求中未檢查令牌,因此失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.