I'm working on a WebGL game with Unity in which I am attempting to call a custom built ASP.NET Web API that's built specifically to work with the game. I've added the code I thought was necessary to get CORS working for making the API requests from the browser, but I keep getting the same error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
I've tried several different variations of how to implement CORS with the API in the program.cs script. I tried:
builder.Services.AddCors(p => p.AddPolicy("corspolicy", build =>
{
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));
And
builder.Services.AddCors(o =>
{
o.AddPolicy("corspolicy", build =>
build.WithOrigins("*")
.AllowAnyMethod()
.AllowAnyHeader()
});
Of course, I also included:
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();
According to the documentation and the tutorials I followed, it looks like I added the correct code in the correct places, but when I publish the API to Azure and try to call it from the WebGL game, I always get that same error that I listed above.
I also tried using the AddDefaultPolicy() with just UseCors(), but that had the same result.
I've tried plugging the URL into Postman and HTTPie along with the header: "Origin": "http://127.0.0.1:5500", to mimic the game running on my local machine, and when I include that, it does return an "Acces-Control-Allow-Origin" header in the response set to either "*" or "http://127.0.0.1:5500" (I've tried both), depending on what I used in WithOrigins().
In Unity I'm making the API call like this:
public void MakeAPIRequest()
{
_webRequest = CreateRequest($"https://apiurl...");
_APICallType = APICallType.login;
_webRequestAsyncOperation = _webRequest.SendWebRequest();
_webRequestAsyncOperation.completed += GetRequestAsyncOperation_completed;
}
private UnityWebRequest CreateRequest(string path, RequestType type = RequestType.GET, object data = null)
{
var request = new UnityWebRequest(path, type.ToString());
if (data != null)
{
var bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data));
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
}
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
return request;
}
I'm currently at a loss for how to get this working, so if anyone here has any advice about what to try or look into, I would really appreciate it.