DEV Community

Irina Scurtu
Irina Scurtu

Posted on • Originally published at irina.codes on

From .NET 2.2 to 3.1 – Routing issues

From 2.2 to 3.1

Having a website on 2.2, I thought that there is about the case to upgrade. Now or never I said. How hard can it be?

I went pretty smooth, by using the -> migration guide..until…. I’ve bumped into routing. I’ve spent a decent amount of time trying to debug the issue, without visible progress.

My issue was that my website had a public side and an Admin area where all the administration magic happens after login.

Changing from app.AddMvc() to app.UseEndpoints() is pretty easy just by changing this:

app.UseMvc(routes =>     {          routes.MapRoute(             name: "areaRoute year",             template: "{area:exists}/{controller}/{action}/{id?}",             defaults: new { controller = "Home", action = "Index" }             );}});

to this:

app.UseEndpoints(endpoints =>{    endpoints.MapControllerRoute(        name: "areaRoute year",        pattern: "{area:exists}/{controller}/{action}/{id?}",        defaults: new {controller = "Home", action = "Index"}    );});

So the real changes in here are the template parameter name to pattern, and MapRouteto MapControllerRoute and the rest is pretty much the same.

So far so good, but my routes on the Admin area simply didn’t work anymore. Everything on the admin was not accessible, and I got 404 in the browser. This led me to believe that my routes had an issue around authorization. I tried again and failed again, and I gave up.

Fortunately, we still have the option to ignore for now the UseEndpoints and fallback to the old version by setting a single property to false in ConfigureServices.

services.AddMvc(options => options.EnableEndpointRouting = false);

Now, by setting this you can use the old approach without any issues, just make sure you don’t add the app.UseRouting() by any means.

Take 2 – try again

Renamed everything as it should be and looked a bit at the order of Midleware imports.

I can say that 3.1 middleware order matters even more than before. You must have

 app.UseRouting();
 //anything in between
 app.UseAuthentication();
 app.UseAuthorization();
 app.UseEndpoints(endpoints =>...);

My actual issue was that app.UseAuthentication() and app.UseAuthorization() order was reversed. I can’t tell you why it worked in 2.2, but for sure doesn’t work anymore in 3.1.

After this fix, I was able to have a fully working app migrated to 3.1, and now I use endpoints not routes.

Conclusion

We knew that order of the middlewares matters, but in this case there is a slight difference. Make sure you have .UseRouting(), any other middleware you need and then UseAuthentication, UseAuthorization, UseEndpoints

The post From .NET 2.2 to 3.1 – Routing issues appeared first on Irina Scurtu.

Top comments (0)