'.NET API rejecting requests based on CORS even when configuration setup
I am trying to send a get request to a .NET API from a VueJS front end. I am getting the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5002/program/getForUser/1. (Reason: CORS request did not succeed). Status code: (null).
I have followed the CORS documentation and set it up as follows in ConfigureServices():
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
I have then made sure to use it in Configure():
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Then my endpoint looks like this:
[ApiController]
[Route("[controller]")]
public class ProgramController : ControllerBase
{
........
[HttpGet]
[Route("getForUser")]
public List<ProgramDbo> GetForUser(int userId)
{
return repository.GetForUser(userId);
}
}
and finally I am trying to make a call from a typescript file:
export async function sendGetRequest(request: string, object?: boolean) {
try {
const response = await fetch(request, {
method: 'GET',
credentials: 'same-origin'
});
const result = object === true ? await response.json() : await response.text();
return result;
} catch (error) {
console.error(error);
}
}
where the url and passed in is https://localhost:5002/program/getForUser/1
I have kestrel listening on 5002 with a new self signed cert:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options => {
options.Listen(IPAddress.Loopback, 5001);
options.Listen(IPAddress.Loopback, 5002, listenOptions =>
{
listenOptions.UseHttps("localhost.pfx", "xxxxxxxx");
});
});
webBuilder.UseStartup<Startup>();
});
What I dont understand is that this worked ages ago, I have recently started up the project again, so I am not sure what changed, even the new SSL cert doesnt seem to have made a difference. I have verified that the endpoint can actually be hit, through postman.
Any help much appreciated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
