【发布时间】:2019-09-22 17:14:20
【问题描述】:
我不能使用 ajax 调用 API,但邮递员调用 API 没问题。我在 .net core 2.2 上开发 web API 并开发 asp.net core MVC。然后我用ajax调用API url "https://localhost:44349" 出现错误,如图1。
API:员工控制器
[HttpPost("CheckAuth")]
public IActionResult checkAuth(EmployeeLoginRequest req)
{
// logic
return Ok(JsonConvert.SerializeObject(employeeLoginResponse));
}
API:启动
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors(
options => options.WithOrigins("https://localhost:44320").AllowAnyMethod()
);
app.UseHttpsRedirection();
app.UseMvc();
}
WEB 应用:Index.cshtml
var data = {
"username": $.trim($("#inputUsername").val()),
"password": $.trim($("#inputPassword").val())
};
$.ajax({
url: "https://localhost:44349/Employee/CheckAuth",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
}
});
我该如何解决?
备注 API 网址:https://localhost:44349 网址:https://localhost:44320
【问题讨论】:
标签: c# asp.net .net ajax asp.net-core