You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Document migration process for SPA projects #44600
app.UseSpa(spa =>{// To learn more about options for serving an Angular SPA from ASP.NET Core,// see https://go.microsoft.com/fwlink/?linkid=864501spa.Options.SourcePath="ClientApp";if(env.IsDevelopment()){spa.UseAngularCliServer(npmScript:"start");}});
Update the targets in the project files to copy the published output to the wwwroot folder:
<TargetName="DebugEnsureNodeEnv"BeforeTargets="Build"Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
<ExecCommand="node --version"ContinueOnError="true">
<OutputTaskParameter="ExitCode"PropertyName="ErrorCode" />
</Exec>
<ErrorCondition="'$(ErrorCode)' != '0'"Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
<MessageImportance="high"Text="Restoring dependencies using 'npm'. This may take several minutes..." />
<ExecWorkingDirectory="$(SpaRoot)"Command="npm install" />
</Target>
<TargetName="PublishRunWebpack"AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<ExecWorkingDirectory="$(SpaRoot)"Command="npm install" />
<ExecWorkingDirectory="$(SpaRoot)"Command="npm run build -- --configuration production" />
<!-- Include the newly-built files in the publish output -->
<ItemGroup>
<DistFilesInclude="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
<ResolvedFileToPublishInclude="@(DistFiles->'%(FullPath)')"Exclude="@(ResolvedFileToPublish)">
<RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
Include the properties to indicate what command to use to start the proxy in development as well as the url to hit:
<PropertyGroup>
<SpaProxyServerUrl>https://localhost:[frontend-port (44416 for example)]</SpaProxyServerUrl>
<SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
</PropertyGroup>
Update launchSettings.json
Add the following environment variable to each of the projects inside the profiles property:
Add the following files in the same folder as package.json
aspnetcore-https.js
// This script sets up HTTPS for the application using the ASP.NET Core HTTPS certificateconstfs=require('fs');constspawn=require('child_process').spawn;constpath=require('path');constbaseFolder=process.env.APPDATA!==undefined&&process.env.APPDATA!==''
? `${process.env.APPDATA}/ASP.NET/https`
: `${process.env.HOME}/.aspnet/https`;constcertificateArg=process.argv.map(arg=>arg.match(/--name=(?<value>.+)/i)).filter(Boolean)[0];constcertificateName=certificateArg ? certificateArg.groups.value : process.env.npm_package_name;if(!certificateName){console.error('Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.')process.exit(-1);}constcertFilePath=path.join(baseFolder,`${certificateName}.pem`);constkeyFilePath=path.join(baseFolder,`${certificateName}.key`);if(!fs.existsSync(certFilePath)||!fs.existsSync(keyFilePath)){spawn('dotnet',['dev-certs','https','--export-path',certFilePath,'--format','Pem','--no-password',],{stdio: 'inherit',}).on('exit',(code)=>process.exit(code));}
proxy.conf.js (replace [IIS-HTTP-PORT] with the IIS port defined in Properties\launchSettings.json):
Update the targets in the project files to copy the published output to the wwwroot folder:
<TargetName="DebugEnsureNodeEnv"BeforeTargets="Build"Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<!-- Ensure Node.js is installed -->
<ExecCommand="node --version"ContinueOnError="true">
<OutputTaskParameter="ExitCode"PropertyName="ErrorCode" />
</Exec>
<ErrorCondition="'$(ErrorCode)' != '0'"Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
<MessageImportance="high"Text="Restoring dependencies using 'npm'. This may take several minutes..." />
<ExecWorkingDirectory="$(SpaRoot)"Command="npm install" />
</Target>
<TargetName="PublishRunWebpack"AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<ExecWorkingDirectory="$(SpaRoot)"Command="npm install" />
<ExecWorkingDirectory="$(SpaRoot)"Command="npm run build" />
<!-- Include the newly-built files in the publish output -->
<ItemGroup>
<DistFilesInclude="$(SpaRoot)build\**" />
<ResolvedFileToPublishInclude="@(DistFiles->'%(FullPath)')"Exclude="@(ResolvedFileToPublish)">
<RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
Include the properties to indicate what command to use to start the proxy in development as well as the url to hit:
<PropertyGroup>
<SpaProxyServerUrl>https://localhost:[frontend-port (44416 for example)]</SpaProxyServerUrl>
<SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
</PropertyGroup>
Update launchSettings.json
Add the following environment variable to each of the projects inside the profiles property:
Add the following files in the same folder as package.json
Add `.env.development
PORT=[frontend-port (44416 for example)]
HTTPS=true
aspnetcore-https.js
// This script sets up HTTPS for the application using the ASP.NET Core HTTPS certificateconstfs=require('fs');constspawn=require('child_process').spawn;constpath=require('path');constbaseFolder=process.env.APPDATA!==undefined&&process.env.APPDATA!==''
? `${process.env.APPDATA}/ASP.NET/https`
: `${process.env.HOME}/.aspnet/https`;constcertificateArg=process.argv.map(arg=>arg.match(/--name=(?<value>.+)/i)).filter(Boolean)[0];constcertificateName=certificateArg ? certificateArg.groups.value : process.env.npm_package_name;if(!certificateName){console.error('Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.')process.exit(-1);}constcertFilePath=path.join(baseFolder,`${certificateName}.pem`);constkeyFilePath=path.join(baseFolder,`${certificateName}.key`);if(!fs.existsSync(certFilePath)||!fs.existsSync(keyFilePath)){spawn('dotnet',['dev-certs','https','--export-path',certFilePath,'--format','Pem','--no-password',],{stdio: 'inherit',}).on('exit',(code)=>process.exit(code));}
aspnetcore-react.js
// This script configures the .env.development.local file with additional environment variables to configure HTTPS using the ASP.NET Core// development certificate in the webpack development proxy.constfs=require('fs');constpath=require('path');constbaseFolder=process.env.APPDATA!==undefined&&process.env.APPDATA!==''
? `${process.env.APPDATA}/ASP.NET/https`
: `${process.env.HOME}/.aspnet/https`;constcertificateArg=process.argv.map(arg=>arg.match(/--name=(?<value>.+)/i)).filter(Boolean)[0];constcertificateName=certificateArg ? certificateArg.groups.value : process.env.npm_package_name;if(!certificateName){console.error('Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.')process.exit(-1);}constcertFilePath=path.join(baseFolder,`${certificateName}.pem`);constkeyFilePath=path.join(baseFolder,`${certificateName}.key`);if(!fs.existsSync('.env.development.local')){fs.writeFileSync('.env.development.local',`SSL_CRT_FILE=${certFilePath}SSL_KEY_FILE=${keyFilePath}`);}else{letlines=fs.readFileSync('.env.development.local').toString().split('\n');lethasCert,hasCertKey=false;for(constlineoflines){if(/SSL_CRT_FILE=.*/i.test(line)){hasCert=true;}if(/SSL_KEY_FILE=.*/i.test(line)){hasCertKey=true;}}if(!hasCert){fs.appendFileSync('.env.development.local',`\nSSL_CRT_FILE=${certFilePath}`);}if(!hasCertKey){fs.appendFileSync('.env.development.local',`\nSSL_KEY_FILE=${keyFilePath}`);}}
Add setupProxy.js inside ClientApp\src (replace [IIS-HTTP-PORT] with the IIS port defined in Properties\launchSettings.json):
Please advise how to workaround some of the limitations of the http-proxy-middleware. For example, in multiple path matching, you cannot use string paths and wildcard paths together. This is not backwards-compatible with the SpaServices approach.
I'd love to ask this on the issue but you keep locking issues and strangling collaboration in order to maintain this course. We're getting further and further away from last-known-good!
Please advise how to workaround some of the limitations of the http-proxy-middleware. For example, in multiple path matching, you cannot use string paths and wildcard paths together. This is not backwards-compatible with the SpaServices approach.
You have full control of how requests are matched, for example:
I'd love to ask this on the issue but you keep locking issues and strangling collaboration in order to maintain this course. We're getting further and further away from last-known-good!
Our announcements repo is locked as it is just the central place for folks to get updates. It is ok to file an issue in the repo explicitly.
In addition it looks like POSTing to the website that relies on the SPA files will now break?
Could you give us a concrete example on how this impacts you?
Not being able to POST to a website? OAuth2 Auth Code flow. POSTing data across micro-frontend modules. I may be misunderstanding the effect of this change in which case please correct me.
Not being able to POST to a website? OAuth2 Auth Code flow. POSTing data across micro-frontend modules. I may be misunderstanding the effect of this change in which case please correct me.
That's not what this change does. The change only prevents the fallback route to be matched on POST requests. The fallback route only matches when no other route matches and returns the default document (index.html).
Based on what you've documented above is this fallback not the mechanism by which SPA pages are loaded? (i.e. index.html in the public folder for the CRA client app)
Does this mean that we can't POST to an ASPNet 7 SPA?
Does this mean that we can't POST to an ASPNet 7 SPA?
No, it does not mean that. It means the following:
If you did not have a route for "/Something/else" defined on the server, the application will serve "index.html" (your SPA). In previous versions it would serve the default document independent of the verb used. That caused problems because the middleware/fallback (it does not matter whether it was the old or the new approach) would handle requests that were meant for the server instead of returning a 404.
The change that we did, constrains when index.html is returned when the route does not match to avoid sending the default document back when the verb is not GET or HEAD.
Maybe this table helps
Before:
Method Server / Route defined
YES
NO
GET
API
index.html
HEAD
API
index.html
POST
API
index.html
PUT
API
index.html
DELETE
API
index.html
After:
Method Server / Route defined
YES
NO
GET
API
index.html
HEAD
API
index.html
POST
API
404
PUT
API
404
DELETE
API
404
Where API just represents a route that your app defines like in a controller or a minimal API.
Activity
javiercn commentedon Nov 10, 2022
Migrating Angular applications from Spa Extensions
Update Startup.cs
AddSpaStaticFiles():UseSpaStaticFiles():UseSpa:app.UseEndpoints(...)add:Update the project file:
Microsoft.AspNetCore.SpaServices.Extensionswith a reference toMicrosoft.AspNetCore.SpaProxy.Update launchSettings.json
Update package.json
Update angular.json
Add the following files in the same folder as package.json
Migrating React applications from Spa Extensions
Update Startup.cs
AddSpaStaticFiles():UseSpaStaticFiles():UseSpa:app.UseEndpoints(...)add:Update the project file:
Microsoft.AspNetCore.SpaServices.Extensionswith a reference toMicrosoft.AspNetCore.SpaProxy.Update launchSettings.json
Update package.json
Add the following files in the same folder as package.json
ClientApp\src(replace [IIS-HTTP-PORT] with the IIS port defined in Properties\launchSettings.json):richstokoe commentedon Nov 21, 2022
Please advise how to workaround some of the limitations of the http-proxy-middleware. For example, in multiple path matching, you cannot use string paths and wildcard paths together. This is not backwards-compatible with the SpaServices approach.
richstokoe commentedon Nov 21, 2022
In addition it looks like POSTing to the website that relies on the SPA files will now break?
aspnet/Announcements#495
I'd love to ask this on the issue but you keep locking issues and strangling collaboration in order to maintain this course. We're getting further and further away from last-known-good!
javiercn commentedon Nov 21, 2022
@richstokoe here is how you can do it.
You have full control of how requests are matched, for example:
javiercn commentedon Nov 21, 2022
Our announcements repo is locked as it is just the central place for folks to get updates. It is ok to file an issue in the repo explicitly.
Could you give us a concrete example on how this impacts you?
richstokoe commentedon Nov 21, 2022
Not being able to POST to a website? OAuth2 Auth Code flow. POSTing data across micro-frontend modules. I may be misunderstanding the effect of this change in which case please correct me.
javiercn commentedon Nov 22, 2022
That's not what this change does. The change only prevents the fallback route to be matched on POST requests. The fallback route only matches when no other route matches and returns the default document (index.html).
richstokoe commentedon Nov 22, 2022
@javiercn Thanks for the reply.
Based on what you've documented above is this fallback not the mechanism by which SPA pages are loaded? (i.e. index.html in the public folder for the CRA client app)
Does this mean that we can't POST to an ASPNet 7 SPA?
javiercn commentedon Nov 22, 2022
No, it does not mean that. It means the following:
If you did not have a route for "/Something/else" defined on the server, the application will serve "index.html" (your SPA). In previous versions it would serve the default document independent of the verb used. That caused problems because the middleware/fallback (it does not matter whether it was the old or the new approach) would handle requests that were meant for the server instead of returning a 404.
The change that we did, constrains when
index.htmlis returned when the route does not match to avoid sending the default document back when the verb is not GET or HEAD.Maybe this table helps
Before:
After:
Where API just represents a route that your app defines like in a controller or a minimal API.
richstokoe commentedon Nov 22, 2022
Thanks for taking the time to explain!
javiercn commentedon Nov 28, 2022
@Rick-Anderson can you add this to the docs?
mkArtakMSFT commentedon Nov 30, 2022
Thanks @Rick-Anderson.
Closing this now, as you have a follow-up issue files.
Thanks @javiercn !