Trying to call an asp .net CORE webAPI from an asp net core mvc website, I always get :
Origin [domain] not found in Access-Control-Allow-Origin header
Main site url like : https://mysite/Login/API_Request
Api url like : https://auth.mysite/api/values
Api work well when I enter the url directly but ajax request not working :
Request :
$(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 Controller
[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);
}
}
I've try with Microsoft.AspNetCore.Cors but I didn't manage to make it working :
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();
}
The code above seems to work, I just publish the API and main site again and it's just work fine. AllowCredentials seems required, I think it's because the API use Windows Authentication but the main site don't. I've change a little bit the authorization on the API statup :
services.AddCors(options => {
options.AddPolicy("AllowAll",
builder =>
{
builder.WithOrigins("http://mysite").WithMethods("GET").AllowAnyHeader().AllowCredentials();
});
});
for some security reasons.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.