Dropsonic.AspNetCore.Routing 1.0.0

dotnet add package Dropsonic.AspNetCore.Routing --version 1.0.0
NuGet\Install-Package Dropsonic.AspNetCore.Routing -Version 1.0.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Dropsonic.AspNetCore.Routing" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Dropsonic.AspNetCore.Routing --version 1.0.0
#r "nuget: Dropsonic.AspNetCore.Routing, 1.0.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Dropsonic.AspNetCore.Routing as a Cake Addin
#addin nuget:?package=Dropsonic.AspNetCore.Routing&version=1.0.0

// Install Dropsonic.AspNetCore.Routing as a Cake Tool
#tool nuget:?package=Dropsonic.AspNetCore.Routing&version=1.0.0

Dropsonic.AspNetCore.Routing

CI Publish

ProducesMatcherPolicy

Overview

A special endpoint MatcherPolicy that selects the endpoint based on the Accept header (or the explicit content type passed as a query string parameter) and ProducesAttribute of the endpoints, thus allowing to have multiple matching endpoints but with different media types in ProducesAttribute.

Scenarios

Consider having a resource that you want to serve, providing a RESTful endpoint to do that.

Sometimes it is very convenient to consider HTML as another representation of this resource, alongside with JSON or XML served by a web API. The original architectural pattern (REST) described in a dissertation by Roy Fielding doesn't mention any specific represenatation formats so serving both HTML and JSON from the same RESTful endpoint is inline with that.

In a real-life scenario, we typically have a single-page application (SPA) that is served from any valid route. The SPA has its own client-side routing, and queries the web API, processing the retrieved data in JSON to display the actual HTML markup.

The suggested approach, when used in conjunction with HATEOAS, provides some major benefits:

  • The SPA doesn't need to know anything about URIs at all (no hardcoded URIs on the client). The SPA is served
  • URIs can have the same format both in API and in SPA routing.

Unfortunately, putting both MVC controller and API controller on the same route in ASP.NET Core produces an AmbiguousMatchException exception since the framework cannot choose an appropriate endpoint. ProducesMatcherPolicy helps with that, choosing the endpoint based on the Accept header, matching its value with the ProducesAttribute on endpoints.

Usage

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddMvc()
            .AddProducesEndpointMatcher(); // (!)
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
using System.Net.Mime;
using Microsoft.AspNetCore.Mvc;

[Route("orders")] // the same route as in the API controller
[Produces(MediaTypeNames.Text.Html)]
public class OrdersController : Controller
{
    [HttpGet("{**catchAll}")] // SPA fallback for client-side routing; an on-site equivalent of MapSpaFallbackRoute()
    public IActionResult Index(string catchAll) => View();
}
using System.Net.Mime;
using Microsoft.AspNetCore.Mvc;

[Route("orders")] // the same route as in the MVC controller
[Produces(MediaTypeNames.Application.Json)]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public IActionResult GetOrders()
    {
        ...
    }
}

You can also find a sample web application in

Behavior

If MvcOptions.RespectBrowserAcceptHeader has a default value of false, ASP.NET Core returns JSON, as stated in the documentation. But in the case when multiple endpoints share the same route (i.e., MVC and web API), it makes sense to default to text/html for user's convenience first, and only if there is no suitable endpoint for that, return application/json.

GET /orders
Accept: */*

-- HTML is served, if possible; JSON is a fallback option

For debug purposes, it is very typical to query the web API directly from the browser and/or 3rd-party tools such as Postman, omitting the Accept header. To support this scenario, you can pass the $format query parameter (similar to OData v3 and OData v4), providing an explicit content type abbreviation:

GET /orders?$format=json
Accept: */*

-- JSON is served

The set of abbreviations and corresponding content types can be customized in the options:

builder
    .AddMvc()
    .AddProducesEndpointMatcher(options =>
    {
        options.UserDefinedFormatToContentTypeMappings["xml"] = new MediaType("application/xml");
    });
GET /orders?$format=xml
Accept: */*

-- An endpoint that produces application/xml is called

Note that this option affects only the ProducesMatcherPolicy behavior and does not affect the default ASP.NET Core content negotiation process. It won't force ASP.NET Core to serve this particular content type, bypassing other content negotiation rules and settings such as MvcOptions.RespectBrowserAcceptHeader.

Remarks

The overall design follows the patterns from Microsoft.AspNetCore.Mvc.Routing.ConsumesMatcherPolicy, especially for the INodeBuilderPolicy implementation.

The unit tests use some techniques heavely inspired by the book Working Effectively with Unit Tests by Jay Fields (Goodreads Author), Michael C. Feathers.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0 382 8/1/2021