CORS ajax post 在 chrome 从 .NET Api 返回 401(未授权)

CORS ajax post returning 401(unauthorized) from .NET Api on chrome

我正在一个简单的预订平台上工作,需要将 CORS(跨源请求)从 jQuery 发送到 .NET Core MVC 上的 Web API 运行ning。

AJAX 调用

我经常发送两个 ajax 请求,一个用于删除,一个用于添加到正在使用 Entity Framework:

的数据库
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,以允许它从我在 "CORSOrigin" 键下的 appsettings.json 中指定的地址:

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 获得授权,但对于 book(reservation) 我一直得到 401(未授权)。

研究

我研究了这个问题几个小时,认为这可能是由不正确的预检请求引起的。我尝试从这些帖子中实施很多解决方案:

另一方面,Somu 用户报告说它适用于 Chrome:


结论

我的问题的特殊之处在于它适用于一种控制器方法,但不适用于另一种控制器方法。这两者的区别仅在于它们使用数据库的方式(添加和删除)。

如果我对某些 .NET 术语不准确,请纠正我。我只用了一个月。感谢任何人的时间和帮助。

这是一个错字,导致了这个问题。在 AJAX 调用中,在 chrome 中不起作用,它说 withcredentials 没有驼峰拼写。 Internet Explorer 可以接受,而其他浏览器不行。