我正在一个简单的预订平台上工作,需要从jQuery向运行在.NET核心MVC上的web API发送COR(跨源请求)。
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身份验证
"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);
}
BookingController.cs
在reguest上被称为:
[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
deleteReservation(reservationID)
ajax获得授权,但对于
book(reservation)
我一直得到401(未经授权)。
研究
结论