Home > Software design >  .NET Core API Endpoint gives 404 only in deployed version
.NET Core API Endpoint gives 404 only in deployed version

Time:09-17

I am building a .NET Core (3.1) Web API which is being hosted in IIS.

I have 2 endpoints:

/api/status

/api/widget/config/{id}

Both endpoints work perfectly when running locally. The /api/status endpoint works in my deployed version too. But the other endpoint gives a 404 error in the deployed version. As it works locally, I believe this to be an issue with how it is deployed. Please can you help me understand the issue?

Here are my 2 controllers code:

[Route("api/[controller]")]
[ApiController]
public class StatusController : ControllerBase
{
    [HttpGet]
    public ActionResult Get()
    {
        return Ok("API is available");
    }
}

and

[Route("api/[controller]")]
[ApiController]
public class WidgetController : ControllerBase
{
    private readonly IWidgetService service;

    public WidgetController(IWidgetService _service)
    {
        service = _service;
    }

    [HttpGet]
    [Route("~/api/[controller]/[action]/{id}")]
    public ActionResult Config(Guid id)
    {
        return Ok(service.GetWidgetConfig(id));
    }
}

and below is my Program.cs and Startup.cs:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            SeedDatabase.Initialize(services);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occured seeding the DB");
        }
    }

    host.Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseKestrel();
            webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
            webBuilder.UseIIS();
            webBuilder.UseStartup<Startup>();
        });

and

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(opts => opts.UseSqlServer(Configuration.GetConnectionString("sqlConnection"),
        options => options.MigrationsAssembly("MyProject")));

    services.AddIdentity<ApplicationUser, IdentityRole>(opt =>
    {
        opt.Password.RequiredLength = 8;
        opt.Password.RequireDigit = true;
        opt.Password.RequireUppercase = true;
        opt.Password.RequireNonAlphanumeric = true;
        opt.SignIn.RequireConfirmedAccount = false;
        opt.SignIn.RequireConfirmedAccount = false;
        opt.SignIn.RequireConfirmedPhoneNumber = false;
    }).AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddScoped<IWidgetService, WidgetService>();

    services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
        builder
        .WithMethods("GET", "POST")
        .AllowAnyHeader()
        .AllowAnyOrigin();
    }));

    services.AddMvc()
        .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/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.UseAuthentication();
    app.UseAuthorization();

    app.UseCors("CorsPolicy");

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

CodePudding user response:

Change your controller code to this:

[Route("api/[controller]")]
[ApiController]
public class WidgetController : ControllerBase
{
    private readonly IWidgetService service;

    public WidgetController(IWidgetService _service)
    {
        service = _service;
    }

    [HttpGet("Config/{id}")]
    public ActionResult Config(Guid id)
    {
        return Ok(service.GetWidgetConfig(id));
    }
}

CodePudding user response:

Change your code like below:-

Startup.cs

app.UseEndpoints(endpoints =>
     {
                endpoints.MapControllers();
     });

Controller:-

[ApiController]
[Route("api/[controller]")]
public class WidgetController : ControllerBase
{
    private readonly IWidgetService service;

    public WidgetController(IWidgetService _service)
    {
        service = _service;
    }

    [HttpGet("Config/{id}")]
    public ActionResult Config(Guid id)
    {
        return Ok(service.GetWidgetConfig(id));
    }
}

Also try your write connection string in appsettings.Development.json file.

It will resolve your issue.

  • Related