Nie działają kontrolery

0

W pliku Program.cs dodałem metdę: app.MapControllers(); oraz przed var app = builder.Build(); metodę: builder.Services.AddControllers();, a kontrolery dalej nie działają. Może ktoś wie jak sprawić aby działały?

Oto kod pliku program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

app.MapControllers();
1
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddControllers();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.MapControllerRoute
(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}"
);

app.Run();

0

@1a2b3c4d5e: Teraz dostaje kod statusu 500 i taka wiadomość:

System.InvalidOperationException: Unable to resolve service for type 'RestaurantApp.Entities.RestaurantDbContext' while attempting to activate 'RestaurantApp.Controllers.RestaurantController'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method2(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

1

No, czyli najprawdopodobniej przyszedł request, miała być już tworzona instancja kontrolera, ale wyszło że nie zrejestrowałeś w kontenerze IoC / Dependency Injection tego, co chcesz aby było wstrzyknięte przez konstruktor do niego.

tl:dr nie masz bazki / EF Cora w Startupie

0

@1a2b3c4d5e: Nie mam pliku Startup.cs. Byłbym wdzięczny gdybyś mi powiedział co mam dokładnie wpisać w konstruktorze, bo ja asp.net core dopiero od tygodnia się ucze więc jestem jeszcze zielony. Tu jest kod kontrolera:

[Route("api/restaurant")]
[ApiController]
public class RestaurantController : ControllerBase
{
    private readonly RestaurantDbContext _dbContext;
    private RestaurantSeeder seeder;
    private readonly IMapper _mapper;

    public RestaurantController(RestaurantDbContext dbContext, IMapper mapper)
    {
        _dbContext = dbContext;
        _mapper = mapper;
        seeder = new RestaurantSeeder(dbContext);
        seeder.Seed();
    }

    [HttpGet]
    public ActionResult<IEnumerable<Restaurant>> GetAll()
    {
        seeder.Seed();
        var restaurants = _dbContext.Restaurants
            .Include(r => r.Address)
            .Include(r => r.Dishes).ToList();

        var restaurantsDto = _mapper.Map<List<RestaurantDto>>(restaurants);

        return Ok(restaurantsDto);
    }
1

w Program.cs

services.AddDbContext<RestaurantDbContext>(options => options.UseSqlServer("conn string"));

+ serio, formatowanie kodu nie jest trudne
screenshot-20220206192422.png

0

@1a2b3c4d5e: "services" mi nie wykrywa

0

builder.Services... jak przy builder.Services.AddControllers();

2

Same problemy przez te minimal API, nie ma Startup i już ludzie się gubią, bo tutoriale się nie zgadzają co do linijki.

0

Teraz dostałem taki wyjątek: System.ArgumentException: „'AddDbContext' was called with configuration, but the context type 'RestaurantDbContext' only declares a parameterless constructor. This means that the configuration passed to 'AddDbContext' will never be used. If configuration is passed to 'AddDbContext', then 'RestaurantDbContext' should declare a constructor that accepts a DbContextOptions<RestaurantDbContext> and must pass it to the base constructor for DbContext.”

W klasie RestaurantDbContext nie mam żadnego konstruktora i nie wiem za bardzo co tam wpisać.

0

a faktycznie chcesz bazy danych użyć? jeśli nie, to możesz ją wywalić z tego controllera RestaurantController(RestaurantDbContext dbContext

oraz nie dodawać tej linijki.

0

chce użyć bazy danych, bo tam metoda pobiera dane z bazy ms sql server.

1

https://entityframeworkcore.com/articles/carloscds-ef-core-dependency-injection

'AddDbContext' was called with configuration, but the context type 'RestaurantDbContext' only declares a parameterless constructor. This means that the configuration passed to 'AddDbContext' will never be used. If configuration is passed to 'AddDbContext', then 'RestaurantDbContext' should declare a constructor that accepts a DbContextOptions<restaurantdbcontext> and must pass it to the base constructor for DbContext.”

W konstruktorze db contextu musisz opcje przyjąć

public RestaurantDbContext(DbContextOptions<RestaurantDbContext> options) : base(options) 
0

@1a2b3c4d5e: Dodłem jeszcze: builder.Services.AddAutoMapper(typeof(Program)); i hula! Dzięki za pomoc!

1 użytkowników online, w tym zalogowanych: 0, gości: 1