I have some issues with calling my ASP.NET Core WebAPI from my Ionic app.
I can see in the developer tools that the data get’s loaded correctly, but Ionic is giving me an error:
data loaded from the api:
CORS is enabled in the api:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddDbContext<TodoContext>(opt =>
opt.UseInMemoryDatabase("TodoList"));
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app)
{
app.UseCors(builder => builder.WithOrigins("http://localhost"));
app.UseMvc();
}
}
I think the error is caused by Ionic or Angular. When I’m loading the data from a public api, everything works fine. I’ve also tried accessing the api with ssl and without.
When you have any questions, feel free to ask me in the comments.
Edit
This is how I call the api:
@Injectable()
export class RestProvider {
apiUrl = 'https://localhost:5001/api';
constructor(public http: HttpClient) { }
getTodoItems() {
return new Promise(resolve => {
this.http.get(this.apiUrl + '/todo').subscribe(data => {
resolve(data);
}, err => {
console.log(err);
});
});
}
}
and this is my controller:
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
private readonly TodoContext _context;
public TodoController(TodoContext context)
{
_context = context;
if (_context.TodoItems.Count() == 0)
{
_context.TodoItems.Add(new TodoItem { Title = "Item1" });
_context.TodoItems.Add(new TodoItem { Title = "Item2" });
_context.SaveChanges();
}
}
[HttpGet]
public ActionResult<List<TodoItem>> GetAll()
{
return _context.TodoItems.ToList();
}
}