1. Web Server 和 API Server 有相同的父網域.
2. Cookie 的網域指定到相同的父網域.
3. 在 API 的 Application 中允許 CORS Request, 需要修改 Startup.cs
3.1 在 ConfigureServices 中要加入 AddCors, 而且要記得 AllowCredentials()
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: "Cors(PolicyName",
builder =>
{
builder.WithOrigins("https://web1.yourdomain.com",
"https://web2.yourdomain.com")
.AllowCredentials();
});
});
services.AddControllers()
.AddNewtonsoftJson(opt =>
opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver());
3.2 在 Configure 中, 要加入 app.UseCors("Cors(PolicyName"), 記得要在 UseAuthorization() 之前.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionMiddleware();
app.UseHttpsRedirection();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
4. 在 Client 端要加上 withCredentials: true
$.ajax({
url: apiRoot + "apiurl",
type: 'GET',
dataType: 'json', // 預期從server接收的資料型態
success: function (res) {
console.log("success: ");
console.log(res);
},
xhrFields: {
withCredentials: true
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("發生錯誤");
}
});