В моем приложении произошла ошибка. Кажется, я не могу определить проблему.C#

Место общения программистов C#
Гость
В моем приложении произошла ошибка. Кажется, я не могу определить проблему.

Сообщение Гость »


Изображение
Я получаю эту ошибку всякий раз, когда хочу получить доступ к своему интерфейсу и Я не знаю, что делать
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 GetAuthors()
{
var authors = await _context.Authors.ToListAsync();
return Ok(authors);
}

[HttpGet("{id}")]
public async Task 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 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(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 YourEntities { get; set; }

public AppDbContext(DbContextOptions options) : base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure your entities and relationships here

// Example configuration for YourEntity
modelBuilder.Entity(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
}
}

Я попробовал это, и, несмотря на все предложения, которые я нахожу в Интернете, я не могу это исправить. Я не знаю, что я делаю не так, поскольку localhost/api/authors также не существует, несмотря на то, что я создал для него конечную точку

Подробнее здесь: https://stackoverflow.com/questions/781 ... he-problem

Вернуться в «C#»