I have enabled the CORS in my c# web API project like following:
Tried to enable CORS globally
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
and ApiController Level
[EnableCors(origins:"*",headers:"*",methods:"*")]
public class MyAppController: ApiController
{
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage TestApi()
{
}
}
Flutter Code
final response =
await http.get(Uri.parse('http://localhost:44310/api/MyApp/TestApi'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return response.body;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
But, neither works and still getting XMLHttpRequest error in Flutter Web.
Also, in the Network Tab, Browser does not show anything for the particular API request.
it hits the API and sends a response from API but not received as a response in Flutter Web.
Reference is taken from here to enable CORS for C# Web Api project attribute: https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Am I missing anything?