Git Product home page Git Product logo

aspnetcore.spayarp's Introduction

AspNetCore.SpaYarp

NuGet
Supported ASP.NET Core versions: 3.1, 5.0, and 6.0

With ASP.NET Core Preview 4, the ASP.NET Core team introduced a new experience for SPA templates. The main benefit of this new experience is that it’s possible to start and stop the backend and client projects independently. This is a very welcome change and speeds up the development process. But it also includes another more controversial change. The old templates served the client application as part of the ASP.NET Core host and forwarded the requests to the SPA. With the new templates, the URL of the SPA is used to run the application, and requests to the backend get forwarded by a built-in proxy of the SPA dev server.

AspNetCore.SpaYarp uses a different approach. Instead of using the SPA dev server to forward requests to the host/backend, it uses YARP to forward all requests that can't be handled by the host to the client application. It works similar to the old templates, but with the advantage of the new templates to start and stop the backend and client projects independently.

The following graphic shows the differences:

Overview

To get more insights you can read my blog post An alternative approach to the ASP.NET Core SPA templates using YARP.

Running the sample

To run the sample, open the solution in Visual Studio and start the AspNetAngularSpaYarp project. It reuses an existing SPA dev server if the client app is already running (started manually in a terminal or VS Code) or it starts a new one.

Debugging

It's possible to debug the .NET code and the SPA at the same time with different editors. To use Visual Studio Code to debug the SPA, create a launch.json file as described in the docs. But instead of the URL of the SPA, the URL of the .NET host must be used.

This is the launch.json file used in the ASP.NET Core 6 sample:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "pwa-msedge",
      "request": "launch",
      "name": "Launch Edge against localhost",
      "url": "https://localhost:7113",
      "webRoot": "${workspaceFolder}"
    }
  ]
}

Using AspNetCore.SpaYarp

Configure settings in project file

<PropertyGroup>
    <!-- SpaYarp configuration -->
    <SpaRoot>ClientApp\</SpaRoot>
    <SpaClientUrl>https://localhost:44478</SpaClientUrl>
    <SpaLaunchCommand>npm start</SpaLaunchCommand>
    <!-- Change the timeout of the proxy (defaults to 120 seconds) 
    <SpaProxyTimeoutInSeconds>120</SpaProxyTimeoutInSeconds> -->
    <!-- Optionally forward only request starting with the specified path 
    <SpaPublicPath>/dist</SpaPublicPath> -->
</PropertyGroup>

ASP.NET Core 6.0 (with WebApplication builder)

Use AddSpaYarp() to register the services and UseSpaYarp() to add the middlware and configure the route endpoint.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// Like with Microsoft.AspNetCore.SpaProxy, a 'spa.proxy.json' file gets generated based on the values in the project file (SpaRoot, SpaProxyClientUrl, SpaProxyLaunchCommand).
// This file gets not published when using "dotnet publish".
// The services get not added and the proxy is not used when the file does not exist.
builder.Services.AddSpaYarp();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // 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.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

// The middlewares get only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
app.UseSpaYarp();

// If the SPA proxy is used, this will never be reached.
app.MapFallbackToFile("index.html");

app.Run();

ASP.NET Core 3.1, 5.0, and 6.0 (with Startup.cs)

Use AddSpaYarp() to register the services, UseSpaYarpMiddleware() to add the middlware, and MapSpaYarp() to configure the route endpoint.

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.AddControllersWithViews();

        // Like with Microsoft.AspNetCore.SpaProxy, a 'spa.proxy.json' file gets generated based on the values in the project file (SpaRoot, SpaProxyClientUrl, SpaProxyLaunchCommand).
        // This file gets not published when using "dotnet publish".
        // The services get not added and the proxy is not used when the file does not exist.
        services.AddSpaYarp();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/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();

        // The middleware gets only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
        app.UseSpaYarpMiddleware();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");

            // The route endpoint gets only added if the 'spa.proxy.json' file exists and the SpaYarp services were added.
            endpoints.MapSpaYarp();

            // If the SPA proxy is used, this will never be reached.
            endpoints.MapFallbackToFile("index.html");
        });
    }
}

Migrate from SpaProxy

This guide assumes that you are using the default ASP.NET Core with Angular Template (but should work the same for other frameworks too).
Thanks to @mdowais for this guide.

Step 1: Add the Nuget Package
https://www.nuget.org/packages/AspNetCore.SpaYarp

Step 2: Remove Old SpaProxy Package
Remove the Package Microsoft.AspNetCore.SpaProxy. As it is not needed for this implementation.

Note: The default template adds a Environment Variable ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy", in the launchSettings.json (Debug Properties in Visual Studio). Which has to be removed, so that you don't see an annoying Exception thrown that "Microsoft.AspNetCore.SpaProxy" is 404.

Step 3: Remove proxy.conf.js
Remove the proxy.conf.js file that contains the proxy config for the client dev server.
And remove the reference to this file from the angular.json file too.

Step 4: Change Project Properties
In your Project Settings (csproj) -> PropertyGroup, change the following

SpaProxyServerUrl to SpaClientUrl
SpaProxyLaunchCommand to SpaLaunchCommand

Step 5: Add the Services and Usings in your Program.cs

// First
builder.Services.AddSpaYarp()

//Second
app.UseSpaYarp();

aspnetcore.spayarp's People

Contributors

berhir avatar buchatsky avatar fuzzlebuck avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.