Feel like I'm doing something silly here, I'm playing around with ASP.NET Core 3 (MVC), doing some tutorials, getting familiar - and I'm having some issues specially with routing.
I have the below code in my Startup.cs
attempting to setup a route of Main/Home/{team}
.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(mvc => mvc.EnableEndpointRouting = true)
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver = new DefaultContractResolver()
)
.AddRazorRuntimeCompilation();
services.AddKendo();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllerRoute(
name: "team",
pattern: "Main/Home/{team}");
//endpoints.MapControllerRoute(
// name: "default",
// pattern: "{controller=Main}/{action=Home}/{id?}");
});
}
On my Main
controller. The action Home
has a single parameter of team
public class MainController : Controller
{
private readonly ILogger<MainController> _logger;
public MainController(ILogger<MainController> logger)
{
_logger = logger;
}
public IActionResult Home(string team)
{
TeamModel model = new TeamModel(team);
return View(model);
}
}
No matter what I do, I cannot get the team
parameter to come through correctly as a route value.
The below configuration gives me a 404
every time, no matter the URL (/Main/Home/MyTeam
or /Main/Home?team=MyTeam
).
Other scenarios either give me the above issue, or the team
parameter comes through with a null
value..
Any help would be great - I think am probably doing something a stupid!
The way you add your endpoint do not have the controller and action that will be called for this route.
You can do something like this:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllerRoute(
name: "team",
pattern: "Main/Home/{team?}",
defaults: new { controller = "Main", action = "Home" });
//endpoints.MapControllerRoute(
// name: "default",
// pattern: "{controller=Main}/{action=Home}/{id?}");
});