Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

asp.net core with angular CLI #3578

Closed
wickdninja opened this issue Dec 15, 2016 · 19 comments
Closed

asp.net core with angular CLI #3578

wickdninja opened this issue Dec 15, 2016 · 19 comments

Comments

@wickdninja
Copy link

Hello,

Sorry this is not really an issue, but I didn't know where else I could reach out to get some insight on a project I have. I recently was tasked with creating a new asp.net core application, and I wanted to used Angular2 (via the angular cli), but I wasn't able to find any good documentation on how to get the two technologies working together. There is a yoeman generator to scaffold a .Net Core app with angular 2, but it doesn't make use of the CLI and uses a static index.cshtml as the root of the application so the links to the script files must also then be static.

I'm a really big fan of the angular-cli so I set out to create a solution that would allow me to take advantage of it. Here is what I've come up with Angular2AspNetCoreStarter but I didn't know where to go to get feedback, and I wanted to share this in case it can solve someone else's need for the cli in their .net core application.

Again I apologize for opening an issue for this, and if there is a more appropriate channel for these types of things I'd be happy to close the issue and move it there.

Thanks again for such a great tool!

@hansl
Copy link
Contributor

hansl commented Dec 15, 2016

(notifying our developer relationship team) @robwormald @StephenFluin @juleskremer Would this be useful somewhere as a reference?

@Brocco we could have a section on our WIKI for this too.

Closing this as it's not an issue.

@hansl hansl closed this as completed Dec 15, 2016
@Brocco Brocco mentioned this issue Dec 15, 2016
38 tasks
@Brocco
Copy link
Contributor

Brocco commented Dec 15, 2016

I added this as a nice-to-have on the documentation tracking issue #2711

@wickdninja
Copy link
Author

thanks for the quick response

@robwormald
Copy link
Contributor

@wickdninja this is great, cheers. We're all traveling at the moment, but I'll forward this over to the people working on templates and such for Asp and VS with angular 👍

@ChuckkNorris
Copy link

ChuckkNorris commented Feb 2, 2017

@wickdninja Would you mind writing up a brief tutorial about how to get Angular 2 running on an ASP.Net Core web server using the Angular CLI? I'd love to learn how to do this from scratch and I can't seem to get Angular to load (after generating a new project in wwwroot)

@juleskremer
Copy link

FYI: we do have some work started on a tutorial which you can see here: angular/angular.io#2850

We are also working on VS templates for ASP.NET but will not look at CLI integration until later in the year.

@wickdninja
Copy link
Author

@ChuckkNorris

@Brocco reached out to me via twitter last week, but unfortunately I have not had the free time to start on the tutorial yet. It's on my schedule for this weekend though.

Would it be more useful to document the workflow I followed to create an Angular2 (via CLI)/ .Net Core project, or should I attempt to contribute to angular/angular.io#2850 ?

@ChuckkNorris
Copy link

ChuckkNorris commented Feb 2, 2017

@wickdninja Exactly - Just the steps to get an Angular 2 app running and hosted on ASP.NET Core.

@juleskremer That tutorial looks like it uses razor so it technically wouldn't be an SPA, right? I'd prefer just to have the NG2 app statically hosted on an ASP.NET Core server.

@ctrl-brk
Copy link

ctrl-brk commented Feb 2, 2017

I started my project this way and then separated the server and the client parts into two different projects. Much more manageable this way and VisualSutido 2015 sucks on editing .ts files.
Actually, the only IDE I know with ability to highlight syntax in internal templates is WebStorm.
Anyway, I run my .net core restful site on one port and separately run Angular app on 4200 using anular cli.
When I make a build for deployment I just tell anular cli to use wwwroot as output folder.
Of course in production you most likely will run both server and client parts on the same port so I prefix all my web service calls with variable from environment.???.ts file. For dev it could be 'http://localhost:60068/api'
and for prod just '/api'

@wickdninja
Copy link
Author

wickdninja commented Feb 6, 2017

@Brocco @ChuckkNorris

Here's my first crack at it.
Repo: https://github.com/wickdninja/DotNetCoreAngular2Demo
ReadMe is the step by step guide. Any feedback would be greatly appreciated.

Copied below as well.

ASP.NET Core / Angular 2 via CLI Quick Start

Disclaimer

This guide was created using the following versions, and provides no guarentee for compatibility with any other versions.

angular-cli: 1.0.0-beta.28.3
node: 7.4.0
os: darwin x64
@angular/common: 2.4.6
@angular/compiler: 2.4.6
@angular/core: 2.4.6
@angular/forms: 2.4.6
@angular/http: 2.4.6
@angular/platform-browser: 2.4.6
@angular/platform-browser-dynamic: 2.4.6
@angular/router: 3.4.6
@angular/compiler-cli: 2.4.6

Install Project Dependencies

  • ASP.NET Core
  • NodeJS
  • Yoeman
    • $ npm i -g yo
  • ASP.NET Core Generator
    • $ npm i -g generator-aspnet
  • Angular CLI
    • $ npm i -g angular-cli

Generate Project

  • $ yo aspnet
    • Select Web Api Project
    • Name application DemoApp
    • $ cd DemoApp

Server Setup

  • Open project.json

    • Exclude node_modules from compilation

      • Add the following to "buildOptions"

        "compile": {
          "exclude": [
            "node_modules"
          ]
        }
    • Add StaticFiles dependency

      • Add "Microsoft.AspNetCore.StaticFiles": "1.0.0" to dependencies
  • Restore dependencies

    • $ dotnet restore
  • Configure server to handle api routes and client side routes

    • Open Startup.cs
      • Locate the Configure method add the following to it
        • Configure CORS

          app.UseCors(cors =>
            cors
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowAnyOrigin()
          );
        • Route requests to root for client side spa

          app.Use(async (context, next) =>
          {
              await next();
              if (context.Response.StatusCode == 404)
              {
                  Console.WriteLine("passing to client");
                  context.Request.Path = "/";
                  await next();
              }
          });
        • Enable static files (without allow directory browsing)

          app.UseFileServer(enableDirectoryBrowsing: false);
        • Setup routes for API

          app.UseMvc(routes =>
          {
              routes.MapRoute(
                    name: "api",
                    template: "api/{controller=Version}/{action=Index}/{id?}");
          });
  • Verify changes by building server

    • $ dotnet build

Client Setup

  • Create a new angular 2 app using the angular CLI
    • $ ng new DemoApp
  • Move angular app to project's root directory
    • $ mv DemoApp/* .
      • This command moves everything except "dot files"
    • Move .editorconfig
      • $ mv DemoApp/.editorconfig .
    • Move git repo
      • $ mv DemoApp/.git .
    • Copy contents of DemoApp/.gitignore into ./gitignore
      • Find and uncomment #wwwroot
        • Remove the # character
    • Remove angular generated app root
      • $ rm -rf DemoApp
  • Configure Angular CLI build output
    • Open angular-cli.json
      • Update outDir
        • "outDir": "wwwroot"
  • Test client app build
    • $ ng build

Build Scripts

  • Open project.json

    • Replace scripts with the following
    "scripts": {
      "ng": "ng",
      "prerestore": "npm install",
      "restore": "dotnet restore",
      "postrestore": "npm run build",
      "prestart": "npm run restore",
      "start": "dotnet run",
      "client": "ng serve",
      "lint": "tslint \"src/**/*.ts\"",
      "test": "ng test",
      "pree2e": "webdriver-manager update --standalone false --gecko false",
      "e2e": "protractor",
      "clean": "rimraf -- wwwroot",
      "postclean": "ng build",
      "prebuild": "npm run clean",
      "build": "dotnet build",
      "clean:prod": "rimraf -- wwwroot",
      "postclean:prod": "ng build --prod",
      "prebuild:prod": "npm run clean:prod",
      "build:prod": "dotnet publish -c release"
    }

Run App

  • $ npm start
    • Wait for server to start
      • Now listening on: http://localhost:5000
    • Verify client application works
      • Open browser and navigate to http://localhost:5000
        • Notice app works! text from our AppComponent is displayed on the screen
    • Verify API is working
      • Navigate to http://localhost://5000/api/values
        • The response should be the following JSON ["value1","value2"]

@sebastiaoherodes
Copy link

@wickdninja Great Work!. Is there a way to use Visual Studio 2015?

@wickdninja
Copy link
Author

@sebastiaoherodes I've used Visual Studio 2015 with a previous project using a similar setup. However, I still used VSCode for client side (angular) development, and only used Visual Studio for .Net code. If I can find some free time this weekend I'll extend the tutorial to include a similar setup. Off the top of my head I think the only differences would be to install the NPM Task Runner extension, disable Typescript compilation in Visual Studio 2015, and then inside the project.json file in the scripts section call the appropriate npm script or angular-cli command.

Such as

  "scripts": {
    "prebuild": "ng build"
}

Do you think this would be a useful addition?

@michael-lang
Copy link

I wrote up a blog post on using Angular CLI inside of a Visual Studio MVC Web application with a different approach. All the relevant commands are included, plus a git repo with the final result and commits for each step along the way that you can review.

http://candordeveloper.com/2017/04/12/how-to-use-angular-cli-with-visual-studio-2017/

Essentially, you have 2 separate projects, a CLI project and an MVC web app (or core app), and a pre-build for the MVC web app does an ng build on the CLI project and copies the few output files to a folder of the MVC app which is then set as a Controller view. See the article for the details.

@juleskremer
Copy link

@michael-lang thanks, I'm on vacation but will review when I return.

@ChuckkNorris
Copy link

@michael-lang also wrote up an article for creating an ASP.NET Core app with the Angular-CLI in a single project.

https://medium.com/@levifuller/building-an-angular-application-with-asp-net-core-in-visual-studio-2017-visualized-f4b163830eaa

@grzech666
Copy link

I tested following: http://www.sparkhound.com/learn/blog/setting-up-an-asp-net-core-project-with-angular-2-utilizing-angular-cli by Vance F., this is the best solution for me,

@challe
Copy link

challe commented Jun 15, 2017

Are there any examples where this has been done together with server side rendering? All of the examples I have found so far uses webpack but I was hoping I could just use the Angular CLI like I do currently.

@maxisam
Copy link
Contributor

maxisam commented Sep 11, 2017

@challe I just put together a repo like what you were asking
https://github.com/maxisam/DotNetCoreNgCli/tree/master/dotNetCoreNgCli

@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Sep 7, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests