Redirects in ASP.NET Core With Both HTML and JSON endpoints

This past week I ran into the problem of retrofitting an endpoint that returns JSON into an app that up until now has returned HTML from all endpoints. It uses cookie authentication, so hitting any route requiring authentication while not logged in would redirect users to a  login page, /account/login in this case. Similarly, hitting any route where you are not authorized would redirect users to /account/forbidden. We can see below that this is done by setting LoginPath and AccessDeniedPath on CookieAuthenticationOptions.

public void ConfigureServices(IServiceCollection services) 
{
    ...
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            options =>
            {
                options.LoginPath = new PathString("/account/login/");
                options.AccessDeniedPath = new PathString("/account/forbidden/");
            });
    ...
}

The problem with this behavior when you start mixing in JSON endpoints is that you still get redirects. The endpoint I was adding requires authentication, so unauthenticated requests were still going through the redirect. Instead of getting back a JSON response with a 401 status code, I was getting redirected to the login page and getting HTML back.

After a brief moment of panic, I figured there had to be a way to solve this. I quickly stumbled across CookieAuthenticationEvents. These let us define functions to handle the same cases we were statically defining above.

public void ConfigureServices(IServiceCollection services) 
{
    ...
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, 
            options => 
            { 
                options.Events = new CookieAuthenticationEvents 
                { 
                    OnRedirectToLogin = SetupRedirect("/account/login/"), 
                    OnRedirectToAccessDenied = SetupRedirect("/account/forbidden/") 
                }; 
            });
    ...
}

Func<RedirectContext<CookieAuthenticationOptions>, Task> SetupRedirect(string redirectPath) 
{ 
    // All requests to /api are JSON API calls and should just return a 401. 
    // All other requests are assumed to use views and the user should 
    // be redirected appropriately. 
    return redirectContext => 
    { 
        if (redirectContext.Request.Path.StartsWithSegments("/api")) 
        { 
            redirectContext.HttpContext.Response.StatusCode = 401; 
        } 
        else 
        { 
            redirectContext.Response.Redirect(redirectPath); 
        } 
        return Task.CompletedTask; 
    }; 
}

Here we can see that we are controlling the behavior based on a convention now. All requests to a route beginning with /api will just return a 401. Requests to any other route will continue to use the same redirect behavior as before.

This was a nice reminder that ASP.NET Core is extremely pluggable. No matter what problem you’re having, there is probably an API you can plug into to solve it.

Creating Custom Assertions With Fluent.Assertions

FluentAssertions logo

I’ve been using Fluent.Assertions for years .NET, but until this week I had never looked into the community extensions. I started adding unit tests to a new controller I was creating in an existing ASP.NET Core MVC project, so I decided to take a look at FluentAssertions.AspNetCore.Mvc.

The primary use case I was unit testing was a controller that returned a ViewResult, but with two different status codes. On the happy path it would return a 200 OK, but if the user did not have the correct role it would return an error page with 401 Unauthorized. Unfortunately, there was no built-in assertion for the status code of a ViewResult.

Luckily, with extension methods we can easily add our own! I cloned the repo for FluentAssertions.AspNetCore.Mvc locally and took a look at how ViewResultAssertions worked. For example, here’s the WithViewName assertion. It tests that the name of the view to render matches the expected view name.

public ViewResultAssertions WithViewName(
    string expectedViewName,
    string reason = "",
    params object[] reasonArgs)
{
    var actualViewName = ViewResultSubject.ViewName;

    Execute.Assertion
        .BecauseOf(reason, reasonArgs)
        .ForCondition(string.Equals(expectedViewName, actualViewName, StringComparison.OrdinalIgnoreCase))
        .WithDefaultIdentifier("ViewResult.ViewName")
        .FailWith(FailureMessages.CommonFailMessage, expectedViewName, actualViewName);
    return this;
}

Using that as an example, it was straightforward to write an extension method to test the status code on a ViewResult. The highlighted lines show how to get the actual status code and then compare it using the FluentAssertions execution API.

public static ViewResultAssertions WithStatusCode(
    this ViewResultAssertions assertions,
    HttpStatusCode expectedStatusCode,
    string reason = "",
    params object[] reasonArgs)
{
    var viewResultSubject = (ViewResult)assertions.Subject;
    var actualStatusCode = (HttpStatusCode)viewResultSubject.StatusCode.Value;

    Execute.Assertion
        .BecauseOf(reason, reasonArgs)
        .ForCondition(expectedStatusCode == actualStatusCode)
        .WithDefaultIdentifier("ViewResult.StatusCode")
        .FailWith("Expected status code {0}, but found {1}", expectedStatusCode, actualStatusCode);
    return assertions;
}

Nothing about this assertion is specific to my project, so I should take the time to submit it as a PR. After writing this, I even found that other result types, like JsonResultAssertion, have almost this exact implementation to check status codes.

The most exciting part to me though was seeing how nice the FluentAssertions execution API is. I’ll definitely be keeping an eye open towards creating my own custom assertion extension methods for repeated test patterns as I continue writing tests.

Dreyfus Model

Your brain on TypeScript

I recently started reading Pragmatic Thinking & Learning: Refactor Your Wetware by Andy Hunt. Very early in the book he describes the Dreyfus model, which provides a framework to think about how people attain and master skills. I thought it would be a good exercise to think through what stage I am at in various skills, especially since I’m absorbing so many new skills all at once at my new job at Husmus.


Stage 1: Novice

Novices are very concerned about their ability to succeed; with little experience to guide them, they don’t know whether their actions will all turn out OK. Novices don’t particularly want to learn; they just want to accomplish an immediate goal. They do not know how to respond to mistakes and so are fairly vulnerable to confusion with things go awry.

Pragmatic Thinking & Learning: Refactor Your Wetware by Andy Hunt

That all sounds very familiar to me and probably does to you as well. We’ve all had to work with a tool we don’t understand at all, but something is going wrong. We don’t have time to build a mental model of how the tool works; we just want to solve our immediate problem and move on. This was me with webpack a couple of weeks ago. I had no clue what I was doing as I customized my Vue build through Vue CLI. Knowing what to change and where was pure cargo cult programming at first.

This is also going to be as we build our engineering team at Husmus. I’ve done a lot of reading on building successful teams over the years, but that is very different from applying those skills. The good news is that I do have good team communication skills, but I’m definitely going to be a novice at managing the power imbalance.

Another good example is the image at the top of this blog post. I generated that using an AI art tool that I have no understanding of and probably never will. To me, it’s just a black box that I enjoy making silly pictures with. That particular one is Your Brain on Typescript.


Stage 2: Advanced Beginner

Advanced beginners can start to break away from the fixed rule set a little bit. They can try tasks on their own, but they still have difficulty troubleshooting.

Pragmatic Thinking & Learning: Refactor Your Wetware by Andy Hunt

This is where I actually am now with webpack and Vue CLI. I know how to customize what webpack is doing under the hood through vue.config.js. I understand how to use vue inspect to see the generated webpack file and where to hook in through vue.config.js to customize as needed. There are limits to my understanding of the underlying webpack config though. Without creating my own config from scratch I probably won’t be able to get to stage 3.


Another good example is Ruby on Rails. I haven’t done deep Rails work since 2012, so my skills have atrophied back to this stage. I was probably in stage 3 back then, but definitely back to stage 2 now.

Stage 3: Competent

At the third stage, practitioners can now develop conceptual models of the problem domain and work with those models effectively. They can troubleshoot problems on their own and begin to figure out novel problems – ones they haven’t faced before. They can begin to seek out and apply advice from experts and use it effectively

Pragmatic Thinking & Learning: Refactor Your Wetware by Andy Hunt


As a jack of all trades, master of none, this stage is my bread and butter. When I need to pick up a new skill, I often level up to this stage and then plateau because I need to move on to something else. Frustratingly, I would put my Docker skills at this level. I know how to do my day-to-day tasks, but it can be a struggle when I need to dig deeper. I’m at the point where giving myself a refresher course and going much deeper is necessary for me to get to stage 4.


Stage 4: Proficient

Proficient practitioners need the big picture. They will seek out and want to understand the larger conceptual framework around this skill. They will be very frustrated by oversimplified information

Pragmatic Thinking & Learning: Refactor Your Wetware by Andy Hunt

One of the defining characteristics of proficiency is being able to reflect and feed those learnings back into your conceptual framework. This perfectly describes my .NET skills. I don’t consider myself an expert, but I have the judgement to know what will and won’t work. Sometimes I can’t explain why and rely on intuition, which I’m getting better at accepting. Being able to reflect and work backwards to discover the root of that intuition is a skill I’m constantly working on though. This is essential when advocating for certain architecture choices that feel right to me, but I can’t consciously explain why off the top of my head.

Stage 5: Expert

Experts are the primary sources of knowledge and information in any field They are the ones who continually look for better methods and ways of doing things… These are the folks who write the books, write the articles, and do the lecture circuit.

Pragmatic Thinking & Learning: Refactor Your Wetware by Andy Hunt

I don’t consider myself an expert in anything and according to the Dreyfus model, you probably shouldn’t either. Only 1 to 5 percent of a population is an expert. So, while I think I’m a proficient .NET programmer, I don’t consider myself an expert. I don’t think I’ve reached that rarified air and I’m not sure if I ever will.

One caveat to this is domain knowledge. If you’ve been working in the same domain for many years and taken a keen interest in learning its ins and outs, then there is a reasonable argument that you are an expert in that domain. As a developer though, this definitely requires learning more than necessary for your immediate job and tasks.