I'm trying to follow Adam Freeman's book "ASP .NET MVC". In this book there is chapter where author suggests putting routes to special configuration file App_Start/RouteConfig.cs
. It looks like nice, but I'm trying to implement it with the help of .Net Core. I had not found special place for routes and I put routes into Startup.cs
. But it looks like pretty ugly. Maybe somebody knows elegant solution for this case?
Here is code of my Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// services are here ..
}
public void Configure(IApplicationBuilder app, IHostingEnvironment 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.UseMvc(routes =>
{
// /
routes.MapRoute(null, "", new
{
controller = "Products",
action = "List",
category = "", page = 1
});
// Page2
routes.MapRoute(null,
"Page{page}",
new
{
controller = "Products",
action = "List",
category = ""
},
new { page = @"\d+" }
);
// Category
routes.MapRoute(null,
"{category}",
new
{
controller = "Products",
action = "List",
page = 1
});
// Category/Page2
routes.MapRoute(null,
"{category}/Page{page}",
new
{
controller = "Products",
action = "List",
},
new
{
page = @"\d+"
});
});
}
}
P.S .Net Core version is 2.2
You can put them in another file:
public static class Routing
{
public static void Include(IApplicationBuilder app)
{
app.UseMvc(routes =>
{
// /
routes.MapRoute(null, "", new
{
controller = "Products",
action = "List",
category = "",
page = 1
});
// Page2
routes.MapRoute(null,
"Page{page}",
new
{
controller = "Products",
action = "List",
category = ""
},
new { page = @"\d+" }
);
}
);
}
}
And then call it in the `Startup' class:
public class Startup
{
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseStaticFiles();
Routing.Include(app);
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With