I have simple asp.net core web api with a nudge controller that returns true for Get request. The PingController.cs looks as follows:
[Route("api/[Controller]")]
public class PingController : Controller
{
[HttpGet]
public IActionResult Get()
{
return Ok(true);
}
}
Why is navigating to the controller (http://localhost:56103/api/Ping)
returning 404 ?
I added route on top of the controller and the HttpMethod for specific action. What is it that I am missing or not understanding here ?
When I add app.UseMvcWithDefaultRoute()
in Startup.cs the controller works fine. (This is also confusing me.)
Startup.cs looks like the following :
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup()
{
Configuration = BuildConfiguration();
}
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
ConfigureRoutes(app);
}
private static void ConfigureMvc(IServiceCollection services, Config config)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)// auto generated
.AddJsonOptions(options => { options.SerializerSettings.Formatting = Formatting.Indented; })
.AddControllersAsServices();
}
private static void ConfigureRoutes(IApplicationBuilder app)
{
//app.UseMvcWithDefaultRoute();
}
}
You need to add UseMvc()
or UseMvcWithDefaultRoute()
in startup to define routing.
UseMvcWithDefaultRoute
adds a default route named 'default' to the request execution pipeline and equals to
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});