Angular 2 routing with Visual Studio & .NET - c#

I completed the "Tour of Heroes" tutorial on Angular 2's website and everything is working great. If I click around, the URL changes and when I refresh, it takes me right where I was before, as you would expect with proper routing.
I want to now use .NET and C# on the backend, so I went through Angular 2's tutorial on getting the project set up with Visual Studio (I was using Sublime Text before). I completed it and got it working, but noticed that the routing only worked when pressing the back/forward buttons. Refreshing didn't work like it did when I just used Sublime and NPM. I went back to the tutorial and found a message at the bottom that concerns me:
"If this application used the Angular router, a browser refresh could return a 404 - Page Not Found. Look at the address bar. Does it contain a navigation url (a "deep link")? We'll have to configure the server to return index.html for these requests. Until we do, remove the navigation path and refresh again."
https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html#!#build-and-run
Does this mean that Angular 2's routing won't work with Visual Studio when I refresh the page no matter what? Is there no hope for Angular 2's routing to fully work when using Visual Studio/.NET/C#?

Angular 2 uses the HTML5 history API. The urls look just like any other site. When you load http://example.com/posts/23 the .NET backend will try to handle it and if it can't will return 404.
That is not what you want.
You want to return the contents of index.html and let Angular handle the rest.
Note that you don't want to redirect to http://example.com/index.html, if you do that it will load angular but you will lose the current path. That way you will never be able to share links to your site.
I assume that you are using the latest version of .NET Core and Visual Studio's templates.
What you need to do:
Install this NuGet package Microsoft.AspNetCore.StaticFiles
Go to Startup.cs and find the Configure method
Add these lines before app.UseMvc();
app.UseDefaultFiles();
app.UseStaticFiles();
Add these lines after app.UseMvc();
app.Run(async context =>
{
context.Response.StatusCode = 200;
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync("./wwwroot/index.html");
});
Add this to the top of the file
using Microsoft.AspNetCore.Http;
For more information look here:
https://docs.asp.net/en/latest/fundamentals/static-files.html
https://angular.io/docs/ts/latest/guide/router.html#!#base-href

Related

.NET Core Razor pages change pages to anonymous

I have a project with .NET Core 2.1 Razor Pages. It was built using the authentication option in the new project UI. So, when I type the URL and hit enter, the website opens the Microsoft login page, and I cannot see any page until I am signed in.
Now, I have a request to change the behavior of the authentication and I need to show the home page (Index) and other pages without the authentication process. So, I think I have to move the login page to a button and allow those pages to be accessible by anyone.
Can you please show me the right direction for this change?
I see that the [AllowAnonymous] directive is only for the controller (ASP.NET Core MVC), because it is not working in the Razor page, where the client and server code are combined in 2 files.
Also, I found a post talking about Service.AddRazorPage but I got an error showing that this method is for MVC, so I don't know if I have to continue with my research to work with this method.
Thanks!
You can try using Razor Pages authorization conventions in ASP.NET Core:
services.AddMvc()
.AddRazorPagesOptions(options =>
{
// options.Conventions.AuthorizePage("/Contact");
// options.Conventions.AuthorizeFolder("/Private");
options.Conventions.AllowAnonymousToPage("/Index");
// options.Conventions.AllowAnonymousToFolder("/Private/PublicPages");
})
// ...
;

What is the difference between UseStaticFiles, UseSpaStaticFiles, and UseSpa in ASP.NET Core 2.1?

ASP.NET Core 2.1.1 offers several seemingly related extension methods for appBuilder:
UseStaticFiles from Microsoft.AspNetCore.StaticFiles
UseSpaStaticFiles from Microsoft.AspNetCore.SpaServices.Extensions
UseSpa from Microsoft.AspNetCore.SpaServices.Extensions
Please help me make sense of their purpose and relation to each other?
Also, is there any difference from the server execution standpoint if I run these methods in a different order
e.g.
app.UseStaticFiles() -> app.UseSpaStaticFiles() -> app.UseSpa()
vs
app.UseSpa() -> app.UseSpaStaticFiles() -> app.UseStaticFiles()
Static files, such as HTML, CSS, images, and JavaScript, are assets an
ASP.NET Core app serves directly to clients. Some configuration is
required to enable serving of these files.
UseStaticFiles - Serve files inside of web root (wwwroot folder)
UseSpaStaticFiles - Serve static file like image, css, js in asset
folder of angular app
UseSpa - let asp.net core know which directory you want to run your
angular app, what dist folder when running in production mode and
which command to run angular app in dev mode
Example
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
UseStaticFiles serves files from wwwroot but it can be changed.
UseSpaStaticFiles does a similar thing but it requires ISpaStaticFileProvider to be registered. If app.ApplicationServices.GetService<ISpaStaticFileProvider>() returns null, then you will get an exception.
throw new InvalidOperationException($"To use {nameof(UseSpaStaticFiles)}, you must " +
$"first register an {nameof(ISpaStaticFileProvider)} in the service provider, typically " +
$"by calling services.{nameof(AddSpaStaticFiles)}.");
So you need to call app.AddSpaStaticFiles() to register default ISpaStaticFileProvider
UseSpa does two things. Rewrites all requests to the default page and tries to configure static files serving. On the contrary to UseSpaStaticFiles it does not throw an exception but just falls back to wwwroot folder.
Actually UseSpaStaticFiles and UseSpa both internally call the same method UseSpaStaticFilesInternal but with a different value for the 3rd parameter which is allowFallbackOnServingWebRootFiles. That is the reason why UseSpaStaticFiles throws an exception if no ISpaStaticFileProvider was registered it simply does not allow to fall back to wwwroot.
BTW if UseSpa falls back to wwwroot internally it calls old good app.UseStaticFiles(staticFileOptions);
Links to github sources:
SpaDefaultMiddleware
SpaStaticFilesExtensions
I've done a deep-dive into how this works recently and I thought I'd explain in detail here, because I don't think it's that well documented. I've investigated how it works with Visual Studio's React template, but it'll work similarly for other SPA frameworks too.
An important point to understand is that, perhaps unlike a more traditional ASP.NET web application: the way your ASP.NET SPA site runs in development is radically different to how it runs in production.
The above is very important to remember because much of the internal implementation of this stuff only applies in production, when you're not routing requests through to a Webpack development webserver. Most of the relevant ASP.NET SPA code is located at this location in the source repo, which I'll be referencing occasionally below. If you want to really dig into the implementation, look there.
IMPORTANT UPDATE:
With .NET 6, Microsoft have completely flipped how this works and now put the Webpack/Vite/whatever SPA dev server in front of the ASP.NET dev server. Frankly, this irrirtates me and I don't like what they've done. I was perfectly happy with the proxying method before. That code is still there, but presumably they will gradually stop supporting it. This sucks. Whatever. I'll leave the guide below, but it applies to the recommended .NET 5 approach, not the .NET 6 one.
How SPA works in ASP.NET
So, to go through the various SPA calls in the order in which they're called by default in the template:
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "ClientApp/build";
});
The comment is slightly misleading, as I'll explain below. This is called in ConfigureServices, and adds in the DefaultSpaStaticFileProvider as an ISpaStaticFileProvider for DI. This is required if you're going to call UseSpaStaticFiles later on (which you probably are). RootPath is specified here (see later on for what it does). Next (remaining calls are made in Configure):
app.UseStaticFiles();
This is good old UseStaticFiles, tried-and-tested way of serving static files from the wwwroot directory. This is called before the others, meaning that if a requested path exists in wwwroot, it will be served immediately from there, and not looked for in the SPA directory (which is ClientApp/public by default during development, or ClientApp/build by default during production - see 'Where do the static assets get served from?' below). If it doesn't exist there, it will fall through to the next middleware, which is:
app.UseSpaStaticFiles();
This is similar to app.UseStaticFiles, but serves static files from a different directory from wwwroot - your 'SPA' directory, which defaults to ClientApp. However, although it can technically work during development, it is only intended to do anything during production. It looks in the above-mentioned RootPath directory - something like ClientApp/build - and tries to serve files from there if they exist. This directory will exist in a published production site, and will contain the SPA content copied from ClientApp/public, and also what was generated by Webpack. However, even though UseSpaStaticFiles is still registered when the site's running in development, it will probably fall through, because ClientApp/build doesn't exist during development. Why not? If you publish your app, the ClientApp/build directory will indeed be created under your project's root directory. But the SPA templates rely on it being deleted during development, because when you run app.UseSpa later on, it eventually runs npm run start, which (if you look in package.json) will run something like:
"start": "rimraf ./build && react-scripts start",
Notice the destruction of the build directory. UseSpaStaticFiles is relying on a npm script being triggered by a later piece of middleware to delete the build directory and effectively stop it from hijacking the pipeline during development! If you manually restore that build directory after starting the site, this middleware will serve files from it even during development. Rather Heath Robinson. As I mentioned above, the comment about React files being served from this directory 'in Production' is slightly misleading because, well, they'll be served from here during development too. It's just that there is an assumption that this directory won't exist during development. Why they didn't just put something like this in the template I'm not sure:
if (!env.IsDevelopment()) {
app.UseSpaStaticFiles();
}
And indeed I'd recommend you put that if clause in so you're not relying on build being deleted from the filesystem.
UPDATE: I've just noticed that this middleware isn't quite as odd as I'd first thought. The DefaultSpaStaticFileProvider actually checks to see whether ClientApp/build exists upon instantiation, and if it doesn't, it doesn't create a file provider, meaning that this will reliably fall through during development when ClientApp/build doesn't exist, even if you restore the directory later. Except that my above description of the behaviour still applies the first time you run the site after publishing, because it's still true that on the first run, ClientApp/build will exist, so this check is a bit of a questionable way of detecting whether static files should never be served (like in a dev environment proxying through to an internal Webpack dev server) or not. I still think my above wrapping of UseSpaStaticFiles in a clause along the lines of if (!env.IsDevelopment()) { ... } is a more reliable and simpler way to do it, and I'm puzzled that they didn't take that approach.
But anyway, this firmware is intended to fall through 100% of the time during development, because the directory should be deleted when the request is made to ASP.NET, to the final middleware:
app.UseSpa(spa => {
//spa.Options.SourcePath = "ClientApp";
// ^ as this is only used in development, it's misleading to put it here. I've moved
// it inside the following 'if' clause.
if (env.IsDevelopment()) {
spa.Options.SourcePath = "ClientApp";
// This is called for the React SPA template, but beneath the surface it, like all
// similar development server proxies, calls
// 'SpaProxyingExtensions.UseProxyToSpaDevelopmentServer', which causes all
// requests to be routed through to a Webpack development server for React, once
// it's configured and started that server.
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
This 'catch-all' middleware rewrites all requests to the 'default page' for the SPA framework you're using, which is determined by spa.Options.DefaultPage, which defaults to /index.html. So all requests will by default render /index.html during production, allowing the client app to always load its page and deal appropriately with requests to different URLs.
However, this middleware is NOT intended to get hit during development, because of what's inside the above if (env.IsDevelopment()) { ... } clause. That UseReactDevelopmentServer (or whatever eventually calls UseProxyToSpaDevelopmentServer, or maybe a direct call to UseProxyToSpaDevelopmentServer) adds a terminal middleware that proxies all requests to a Webpack development server, and actually prevents requests from going through to the UseSpa middleware. So, during production, this middleware runs and acts as a "catch-all" to render index.html. But during development, it is not indended to run at all, and requests should be intercepted first by a proxying middleware that forwards to a Webpack development server and returns its responses back. The Webpack development server is started in the working directory specified by spa.Options.SourcePath, so it will serve ClientApp/public/index.html as the catch-all webpage during development (/public/??? See below.) The spa.Options.SourcePath option is not used during production.
Where do the static assets get served from?
Take a given request for a file /logo.png. wwwroot will first be checked, and if it exists there, it will be served. During production, ClientApp/build will then be checked for the file, as that was the path configured in services.AddSpaStaticFiles. During development, however, this path is effectively not checked (it is, but it should always have been deleted before development starts; see above), and the path that will get checked for static assets instead is ClientApp/public in your project's root directory. This is because the request will be proxied through to an internal Webpack development server. The Webpack development server serves both dynamically-generated Webpack assets, but also static assets like /logo.png, from its "static directory" option, which defaults to public. Since the server was started in the ClientApp working directory (thanks to the spa.Options.SourcePath option), it will try to serve static assets from ClientApp/public.
In summary - execution flow
Basically, ASP.NET's SPA methods are trying to roughly emulate at production what the Webpack development server does at development - serve static assets first (although ASP.NET also tries wwwroot first, which the Webpack dev server obviously doesn't do), then fall through to a default index.html for the SPA app (the Webpack dev server doesn't do this by default, but things like react-scripts have a default setup which adds a plugin causing this to happen).
However, at development, ASP.NET actually does proxy requests through to that Webpack dev server, so its SPA middleware is basically meant to get bypassed. Here's a summary of the intended flow in both cases:
Production:
Request
-> Check in /wwwroot
-> Check in /ClientApp/build
-> Rewrite request path to /index.html and serve that from /ClientApp/build
Development:
Request
-> Check in /wwwroot
-> Proxy through to internal Webpack dev web server, which:
-> ... serves static assets from /ClientApp/public
-> ... serves dynamically-generated Webpack assets from their locations
-> ... failing that, rewrites request path to /index.html and serves that from /ClientApp/public
An additional WTF
Microsoft made a few design decisions I think are a bit questionable with how they did this, but one behaviour makes no sense to me and I have no idea of its use-case, but it's worth mentioning.
app.UseSpa ends up calling app.UseSpaStaticFilesInternal with the allowFallbackOnServingWebRootFiles option set to true. The only time that has an effect is if you didn't previously add an ISpaStaticFileProvider to DI (eg. by calling services.AddSpaStaticFiles), and you call app.UseSpa anyway. In that case, instead of throwing an exception, it will serve files from wwwroot. I honestly have no idea what the point of this is. The template already calls app.UseStaticFiles before anything else, so files from wwwroot already get served as top priority. If you remove that, and remove services.AddSpaStaticFiles, and don't call app.UseSpaStaticFiles (because that'll throw the exception), then app.UseSpa will serve files from wwwroot. If that has a use-case, I don't know what it is.
Further thoughts
This setup works OK, but the 'on-demand' setup of the Webpack development server seems to spin up a ton of node instances, which seems rather inefficient to me. As suggested under 'Updated development setup' in this blog (which also provides some good insights into how this SPA stuff works), it might be a better idea to manually run the Webpack development server (or Angular/React/whatever) at the beginning of your development session, and change the on-demand creation of a dev server (spa.UseReactDevelopmentServer(npmScript: "start")) to on-demand creation of a proxy to the existing dev server (spa.UseProxyToSpaDevelopmentServer("http://localhost:4200")), which should avoid spinning up 101 node instances. This also avoids some unnecessary slowness of rebuilding the JS each time something in the ASP.NET source changes.
Hmm... MS went to so much effort to allow that proxying through to a node-backed Webpack development web server, it would almost be simpler if they just recommended that in production, you deploy a node-based web server to proxy all SPA requests through to. That would avoid all the extra code which acts differently in production and development. Oh well, I guess that this way, at least when you get to production, you're not reliant on node. But you pretty much are at development. Probably unavoidable given how all the SPA ecosystems are designed to work with node. When it comes to SPA applications, node has effectively become a necessary build tool, akin to the likes of gcc. You don't need it to run the compiled application, but you sure need it to transpile it from source. I guess hand-crafting the JavaScript to run in the browser, in this analogy, would be like hand-writing the assembly. Technically possible, but not really done.

ASP NET Web API google authentication issue HTTP 404

I am trying to setup a social login for my site.
Here is what I did:
I created credentials on google and have both ClientID and Secret
In default MVC app, in App_Start Startup.Auth.cs I uncommented
app.UseGoogleAuthentication()* method, so it looks like this:
Build solution!
Made sure authorized JavaScript origins and Redirect url are correct. And other things that are needed on console.cloud.google.com are done. Including activation of Google+ API
Eventually Google authentication button should appear in _ExternalLoginsListPartial partial view. But as I can see I have 0 login providers still. And not sure why, and what can I do about it?
var loginProviders = Context.GetOwinContext().Authentication.GetExternalAuthenticationTypes();
//loginProviders.Count() here returns 0
Tried researching, but most are saying that you forgot to build, or restart the server. Tried that but nothing changed.
As last resort, I tried following a tutorial https://youtu.be/WsRyvWvo4EI?t=9m47s
I did everything as shown there, I should be able to reach api/Account/ExternalLogins?returnUrl=%2F&generateState=true url, and receive callback URL from Google.
But I got stuck with same HTTP404 error at 9:50
To answer my question, everything turns out to be fine.
All I had to do was just to give it some time.
After couple of hours, Google provider appeared on the page.
For future readers - if met with 404 in this case, another possibility is an active filtering rule against query strings in IIS. One of the commonly copy-pasted rules aiming to block SQL injection requests scans the query string for open (to catch OPEN cursor). Your OAuth request probably contains this word in the scopes section (data you want to pull from the Google profile)
IIS -> Request Filtering
Switch to the tab "Rules"
Inspect and remove any suspicious active filters there

ASP.NET MVC 4 Internet Application Template OAuth RegisterGoogleClient Unsuccessful

I created a Visual Studio ASP.NET MVC 4 Internet Application Template project. I immediately went into the AuthConfig class and uncommented this line:
//AuthWebSecurity.RegisterGoogleClient();
I then ran the application. I clicked 'Log in', then 'Google'. I am redirected to Google where I sign in and then get redirect to the 'ExternalLoginCallback' action in the Account controller. In the debugger these line get executed:
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
No matter what I do the results variable's IsSuccessful property is set to false. I am just wondering what I am doing incorrectly considering I am using the provided template? I have no idea how I can retrieve an error messages from OAuthWebSecurity.VerifyAuthentication to determine what is going on.
Any help is appreciated!
Note: I have tried updating all NuGet packages. I've also tried Microsoft (didn't work because a redirect url + localhost issue) and LinkedIn (didn't work, unsure why but receiving bad request 400 error) OAuth Clients.
I found a Google OAuth2 implementation that I was able to easily get working:
https://github.com/mj1856/DotNetOpenAuth.GoogleOAuth2

Google+ signin "Getting Started" project - problems with IIS

Using the C#/.NET Google+ sign-in quick start project, I'm hitting problems with IIS6. Here are the steps I followed:
downloaded the project from Github
modified the index.html and signin.ashx files to contain my Client ID and Client Secret
running the project on my machine (using the built in web server for Visual Studio 2010) works fine
published to Windows 2003 server with IIS6
added "index.html" as a default document for the web site
set the web site to use an app pool configured for the 4.0 .NET framework
attempted to access the page from Chrome
Accessing the site with no page specified on the URL (https://myserver.com/gplussample/) brings up the Google+ signin button. This works great and I'm taken to the page with my profile photo, circles, etc.
However, when I click the "disconnect" button, nothing happens. Using Chrome DevTools to examine the process, I see this error:
POST https://myserver.com/gplussample//disconnect 404 (Not Found)
The problem is the //disconnect - there's no page name (I believe it should be signin.ashx, as that's what works when I'm running the app on the dev web server with Visual Studio 2010).
I then attempted to access the site with a page name specified:
https://myserver.com/gplussample/signin.ashx
That results in a blank page and again, looking at the Chrome DevTools, I see a 400 Bad Request error for the .ashx handler. I searched and searched for solutions for .ashx handlers and "bad request" errors, with no success in this particular case.
Thinking IIS6 was the culprit, I published the site to an IIS7 instance.
With no page name specified on the URL (http://localhost/gplusoriginal/), I encountered the same error with the "disconnect" button - no action and a 404 error.
When I changed the URL to http://localhost/gplusoriginal/signin.ashx, I received this error:
Could not create type 'GPlus_ServerSideFlow.Signin'.
Again, back to Google and checking on .ashx handlers and issues with IIS7. I found a post about the web.config and specifying the handler there, so I tried that.
<system.webServer>
<handlers>
<add name="GPlus_ServerSideFlow.Signin" path="*.ashx" verb="*"
type="GPlus_ServerSideFlow.Signin" resourceType="Unspecified" />
</handlers>
</system.webServer>
Adding this snippet to the web.config resolved the "could not create type" error, but resulted in another 400 Bad Request error.
So, my questions are: What has to be done with II6 or IIS7 to get this sample project working? Are there additional steps in configuring IIS that need to be completed? Or something missing from the project code?
Thank you
The way that the sample works is that the RESTful endpoints are intercepted by an ashx handler, signin.ashx.cs. The handler can't be directly addressed so routes are setup in global.ashx.cs to map endpoints (/, /connect, /disconnect, etc) to that route handler.
As the sample ships, it assumes the built-in web server running on the root port. When moving to IIS, you need to change the path matchers from Equals to EndsWith in order to match the virtual directory you are deploying to:
// Redirect base path to signin.
if (context.Request.Path.EndsWith("/"))
{
context.Response.RedirectPermanent("signin.ashx");
}
// This is reached when the root document is passed. Return HTML
// using index.html as a template.
if (context.Request.Path.EndsWith("/signin.ashx"))
{
Apologies for the delay on this... but hopefully that fixes it! This fork of the C# starter has the changes in it, tested with IIS, and this update may end up getting merged back into the official sample soon.

Categories