【发布时间】:2017-12-15 13:59:51
【问题描述】:
我正在开发一个简单的预订平台,需要将 CORS(跨源请求)从 jQuery 发送到在 .NET Core MVC 上运行的 Web API。
AJAX 调用
我经常发送两个 ajax 请求,一个要删除,一个要添加到使用实体框架的数据库:
var deleteReservation = function (reservationID) {
var u = $.ajax({
url: url+"/api/booking/del",
method: "POST",
async: true,
xhrFields: {
withCredentials: true
},
data: { "id": reservationID }
}).done(function (data) {
refresh();
});
};
var book = function (reservation) {
var u = $.ajax({
url: url + "/api/booking/new",
method: "POST",
async: true,
xhrFields: {
withcredentials: true
},
data: { "reservation": JSON.stringify(reservation) }
}).done(function (data) {
console.log(data);
refresh();
});
};
实现 Windows 身份验证
我需要通过 Windows 身份验证对这些请求进行授权。我已经在 API 上设置了 CORS,以允许它从我的 appsettings.json 中在 "CORSOrigin" 键下指定的地址:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors();
services.AddRouting();
services.AddEntityFrameworkSqlServer();
services.AddDbContext<BookingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BookingContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(builder =>
builder.WithOrigins($"{Configuration["CORSOrigin"]}").AllowAnyHeader().AllowCredentials());
app.UseMvc();
DbInitializer.Initialize(context);
}
API 控制器
最后,这是我在BookingController.cs 中的两个应要求调用的方法:
[Route("api/[controller]")]
[Authorize]
public class BookingController : Controller
{
private readonly BookingContext context;
public BookingController(BookingContext context)
{
this.context = context;
}
[HttpPost("new")]
public IActionResult book(String reservation) {
var r = JsonConvert.DeserializeObject<Reservation>(reservation);
context.Reservations.Add(new Reservation(r.SeatID, r.User, r.Date));
context.SaveChanges();
return Ok();
}
[HttpPost("del")]
public IActionResult deleteReservation(int id) {
var r = context.Reservations.SingleOrDefault(x => x.ID == id);
if (r == null) return NotFound("Can't found requested reservation.");
context.Reservations.Remove(r);
context.SaveChanges();
return Ok();
}
}
问题:使用 IE,而不是 Chrome
现在的问题是所有请求都在 Internet Explorer 中完美运行,并且我能够使用 Windows 身份验证,但是,当我在 Chrome 或 Opera 中运行这些请求时,deleteReservation(reservationID) ajax 被授权,但对于 @987654332 @ 我不断收到 401(未授权)。
研究
我在这个问题上玩了几个小时,然后想到它可能是由不正确的预检请求引起的。我尝试从这些帖子中实施很多解决方案:
- POST AJAX request denied - CORS?
- WebAPI CORS with Windows Authentication - allow Anonymous OPTIONS request
- Web API 2.1 Windows Authentication CORS Firefox
- AJAX Post JQuery does not working CORS
另一方面,Somu 用户报告说它可以在 Chrome 中运行:
结论
我的问题的特殊之处在于它在一种控制器方法中有效,但在另一种方法中无效。这两者的区别仅在于它们使用数据库的方式(添加和删除)。
如果我对某些 .NET 术语不准确,请纠正我。我只用了一个月。感谢任何人的时间和帮助。
【问题讨论】:
标签: ajax asp.net-web-api cors windows-authentication unauthorized