我无法使用Ajax调用api,但可以进行邮递员调用

时间:2019-05-04 11:20:04

标签: c# asp.net .net ajax asp.net-core

我不能使用ajax调用API,但是邮递员调用API可以。我在.net core 2.2上开发了Web API,并开发了asp.net core MVC。然后,我使用对API网址“ https://localhost:44349”的ajax调用,在图1中发生了错误。

API:EmployeeController

[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

Figure 1

2 个答案:

答案 0 :(得分:0)

您需要启用CORS才能解决此问题, 请按照以下步骤操作: https://www.c-sharpcorner.com/article/enabling-cors-in-asp-net-core-api-application/

如果您已经启用它,那么请检查下面的URL并尝试这些步骤。 Missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel

答案 1 :(得分:0)

尝试更改为此:

app.UseCors(
    options => options.WithOrigins("https://localhost:44349").AllowAnyMethod()
);