Home > Net >  NET 6: Controller method is not reachable
NET 6: Controller method is not reachable

Time:12-03

I have a simple NET 6 application. added a controller and trying to test.

Run it, I see method on Swagger page, execute the method in Swagger, it returns 200, but it does not return "Hello World". Then I have added logger output to the controller constructor and to the method - no outputs. What can be the reason of the problem? My Program file

using MTApp.Infra;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddMvc();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(1800);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});
//builder.Services.AddSession();// !
var app = builder.Build();
app.UseSession(); //<--- add this line
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "MTApp API V1");
    });
}
app.UseTenant();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

The extension:

public static class TenantSecurityMiddlewareExtension
{
    public static IApplicationBuilder UseTenant(this IApplicationBuilder app)
    {
        app.UseMiddleware<TenantSecurityMiddleware>();
        return app;
    }
}

and my controller

using Microsoft.Extensions.Logging;
namespace MTApp.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class DobedoController : ControllerBase
    {
        private readonly ILogger<DobedoController> _logger;
        public DobedoController(ILogger<DobedoController> logger)
        {
            _logger = logger;
            _logger.LogInformation("DobedoController");
        }
        [HttpGet("GetHW2")]
        public string GetHW2()
        {
            _logger.LogInformation("DobedoController:HW2");
            return "Hello World2";
        }
    }
}

CodePudding user response:

What is app.UseTenant(); supposed to do?

Becase it works for me after:

  • Creating a new .NET 7 web api using dotnet new webapi.

  • Replacing the template controller with yours (missing using Microsoft.AspNetCore.Mvc; line at the top, but you probably have that in the global usings).

  • Replacing the template Program.cs with yours.

  • Commenting the line with app.UseTenant() (since it comes from MTApp.Infra).

  • Related