I get this error whenever I want to access my frontend and I don't know what to do
Author Controller cs
// Controllers/AuthorController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Pencraft.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AuthorController : ControllerBase
{
private readonly AppDbContext _context;
public AuthorController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Author>>> GetAuthors()
{
var authors = await _context.Authors.ToListAsync();
return Ok(authors);
}
[HttpGet("{id}")]
public async Task<ActionResult<Author>> GetAuthor(int id)
{
Author? author = await _context.Authors.FindAsync(id);
if (author == null)
{
// Return NotFound result if author is null
return NotFound();
}
// Return the author value
return Ok(author);
}
// Other actions for creating, updating, and deleting authors
// Additional action method examples
[HttpPost]
public ActionResult<Author> CreateAuthor(Author newAuthor)
{
// Your logic to create a new author
// ...
// Return the newly created author
return Ok(newAuthor);
}
[HttpPut("{id}")]
public IActionResult UpdateAuthor(int id, Author updatedAuthor)
{
// Your logic to update the author with the specified id
// ...
// Return NoContent if successful
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteAuthor(int id)
{
// Your logic to delete the author with the specified id
// ...
// Return NoContent if successful
return NoContent();
}
}
}
Startup.cs
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Pencraft_app.pencraft_backend
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Pencraft_app.pencraft_backend")));
// Other services can be added here...
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// Production configuration goes here
}
app.UseRouting();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCors("AllowOrigin"); // Make sure this is before UseRouting()
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapRazorPages();
// Conventional routing for API controllers
endpoints.MapControllerRoute(
name: "default",
pattern: "api/{controller}/{action=Index}/{id?}");
// If you still want a specific route for "AuthorApi," you can add it separately
endpoints.MapControllerRoute(
name: "AuthorApi",
pattern: "api/author",
defaults: new { controller = "Author", action = "Index" });
});
}
}
public class AppDbContext : DbContext
{
public DbSet<YourEntity> YourEntities { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure your entities and relationships here
// Example configuration for YourEntity
modelBuilder.Entity<YourEntity>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.Name).IsRequired();
// Add other property configurations as needed
});
}
}
public class YourEntity
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
// Add other properties as needed
}
}
I tried this and despite every suggestion I find online, I cannot seem to fix this. I don't know what I'm doing wrong as the localhost/api/authors also doesn't exist despite me creating an endpoint for it
You might have the answer in your own code!
In your startup.cs you have
This states you need to have the app.UseCors("AllowOrigin") before your useRouting(). So change that section to: