簡體   English   中英

在Access-Control-Allow-Origin標頭中找不到源[域]。 ASP .NET CORE API MVC

[英]Origin [domain] not found in Access-Control-Allow-Origin header. ASP .net CORE API mvc

嘗試從asp net core mvc網站調用asp .net CORE webAPI,我總是得到:

在Access-Control-Allow-Origin標頭中找不到源[域]

主站點網址,例如: https://mysite/Login/API_Request
像這樣的api網址: https://auth.mysite/api/values

當我直接輸入網址但ajax請求不起作用時,api可以正常工作:

要求:

$(document).ready(function () {
getIdentity();
});

function getIdentity() {
$.ajax({
    type: "GET",
    data: "",
    url: "https://auth.mysite/api/values",
    dataType: 'json',
    xhrFields: {
        withCredentials: true
    },
    contentType: false,
    processData: false,
    success: function (response) {
        response = response.replace(/\"/g, "");
        console.log(response);
    },
    error: function (response) {
        console.log(response.statusText);
    }
});
}

API控制器

[Authorize]
[Route("api/[controller]")]
[EnableCors("AllowAll")]
  public class ValuesController : Controller
    {
    [HttpGet]
    public ActionResult Get()
    {
        var u = User;

        WindowsIdentity identity = null;

        if (HttpContext== null)
        {
            identity = WindowsIdentity.GetCurrent();
        }
        else
        {
            identity = HttpContext.User.Identity as WindowsIdentity;
        }
        return Json(identity.User.Value);
    }
}

我嘗試使用Microsoft.AspNetCore.Cors,但沒有設法使其正常工作:

startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                        builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials();
                    });
            });
         ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors("AllowAll");


            app.UseMvc();

        }

上面的代碼似乎可以正常工作,我只是再次發布了API和主站點,一切正常。 AllowCredentials似乎是必需的,我認為這是因為API使用Windows身份驗證,但主站點卻沒有。 我對API狀態的授權做了一些更改:

services.AddCors(options => {
                options.AddPolicy("AllowAll",
                    builder =>
                    {
                      builder.WithOrigins("http://mysite").WithMethods("GET").AllowAnyHeader().AllowCredentials();
                    });
            });

出於某些安全原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM