代码之家  ›  专栏  ›  技术社区  ›  padr

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

  •  1
  • padr  · 技术社区  · 7 年前

    我正在一个简单的预订平台上工作,需要从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(未经授权)。

    研究


    结论

    1 回复  |  直到 7 年前
        1
  •  1
  •   padr    7 年前

    这是造成这个问题的打字错误。它说,在AJAX调用中,在chrome中不起作用 withcredentials