Azure Controllers with Razor

Do you run into the occasional odd problem building ASP.NET Core applications that are hard to debug? Today I'll show how to go play detective on some of these.

But first, let's set the stage.

Adding authentication

I have been learning more and more about what goes into making up the Microsoft identity platform, and I generally like what I see.

If you happen to be on a platform that's not well supported is, well that's never fun, but there are plenty of open standards and open source code repositories to help you along.

I was doing some vanilla ASP.NET Core Razor Pages work the other day. Sign-in visitors came up. There are lots of resources, documentation, and full-on libraries for the Microsoft stack, so I decided to go with that.

I was following along with one of the samples (there are many, many samples), but somehow the links to sign-in wouldn't be properly generated.

The issue

The links I refer to are snippets that say something like: a class="nav-link text-dark" asp-area="AzureAD" asp-controller="Account" asp-action="SignIn"

What's up with that? Time to investigate.

First, I looked up the extra asp-* properties. The syntax itself is part of the anchors tag helper feature.

The asp-controller and asp-area attribute names seem generic, but together with asp-area they strongly suggest we're really talking in Model-View-Controller terms, as everything lines up quite well.

So there's a properly referenced controller, but I don't have any controllers in my project - I'm using Razor pages. I looked for dependencies instead, and realized I had added Microsoft.AspNetCore.Authentication.AzureAD.UI along the way.

A search for Microsoft.AspNetCore.Authentication.AzureAD.UI github lands me here, where I immediately notice the Areas folder. Digging in, I finally find the AccountController I was looking for!

This was very obviously an MVC thing, and it turns out that the new Razor-based projects do not include some of the classic MVC support that the service-side library is trying to use. So time to wire that up.

The fix

To fix this, simply add this to ConfigureServices in your Startup.cs file:

services.AddControllers();

And make sure you map controller endpoints when you're setting them up in your Configure call:

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

That it! Now the controller will respond properly and, if you followed the rest of the sample or tutorial correctly, you should have a nice functioning app.

Happy endpoint mapping!

Tags:  dotnet

Home