关于.NET Core 2.0 MVC、Web API与Angular/AngularJS项目搭建的咨询
Hey there! Let's tackle your questions about building a .NET Core 2.0 project with MVC, Web API, and Angular 4—first we'll cover whether to combine them into one project or split them, then walk through the full setup process.
Both approaches work, but which one you pick depends on your team size and project complexity:
- Single project: Great for small to mid-sized teams or projects where frontend and backend developers collaborate closely. It simplifies deployment and avoids cross-origin resource sharing (CORS) headaches since everything runs on the same domain.
- Separate projects: Better for large teams where frontend and backend teams work independently, or if you plan to scale the API separately (e.g., serve multiple frontends from the same API). You'll need to configure CORS to allow the frontend to access the API.
For most cases, starting with a single project is simpler—let's focus on that first, then cover the separate project flow as an alternative.
Step 1: Create the .NET Core 2.0 MVC project
You can use either Visual Studio or the .NET CLI:
- Using CLI: Run this command in your terminal:
dotnet new mvc -n MyAspNetCoreAngularApp cd MyAspNetCoreAngularApp - Using Visual Studio: Create a new "ASP.NET Core Web Application" project, select "MVC" and target .NET Core 2.0.
Step 2: Add Web API functionality
.NET Core MVC and Web API are unified in .NET Core, so you don't need a separate project. Just add an API controller:
- Right-click the
Controllersfolder → Add → Controller → Select "API Controller - Empty" → Name itValuesController. - Update the controller code to include the required attributes and a test endpoint:
using Microsoft.AspNetCore.Mvc; namespace MyAspNetCoreAngularApp.Controllers { [ApiController] [Route("api/[controller]")] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public IActionResult Get() { return Ok(new string[] { "value1", "value2" }); } } }
Test it by running the project and visiting https://localhost:<port>/api/values—you should see the JSON response.
Step 3: Integrate Angular 4
Angular 4 requires an older version of the Angular CLI, so first install the compatible version globally:
npm install -g @angular/cli@1.7.4
Then set up the Angular project inside your .NET Core app:
- In your project root, run:
This creates an Angular 4 app in theng new ClientApp --style css --routing falseClientAppfolder. - Configure .NET Core to serve the Angular app:
- Open
Startup.csand update theConfigureServicesmethod to add SPA static files support:using Microsoft.AspNetCore.SpaServices.AngularCli; public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Add SPA support services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); } - Update the
Configuremethod to serve the Angular app:public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // ... existing middleware (error handling, static files, routing) app.UseSpaStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); }
- Open
- Update Angular to call your API:
- Open
ClientApp/src/app/app.component.tsand add a method to fetch data from the API:import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; values: string[]; constructor(private http: HttpClient) {} ngOnInit() { this.http.get('/api/values').subscribe((data: string[]) => { this.values = data; }); } } - Update
ClientApp/src/app/app.component.htmlto display the data:<h1>{{title}}</h1> <ul> <li *ngFor="let value of values">{{value}}</li> </ul>
- Open
Step 4: Test the full stack
Run the .NET Core project—during development, it will automatically start the Angular dev server. You should see the Angular app displaying the values from your API.
If you prefer separate projects:
Create the Web API project:
dotnet new webapi -n MyApi cd MyApiAdd CORS support in
Startup.csto allow your frontend to access it:public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAll", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // ... existing middleware app.UseCors("AllowAll"); app.UseMvc(); }Create the MVC project (optional, if you still need server-side views):
dotnet new mvc -n MyMvcOr skip the MVC project and just use Angular as your frontend.
Create the Angular 4 project:
ng new MyAngularFrontend --style css --routing falseUpdate the API call in Angular to use the API's full URL (e.g.,
http://localhost:5000/api/values).
- Backend architecture: Use a layered approach—separate your data access (Repository pattern), business logic (Service layer), and API controllers to keep code maintainable.
- Frontend structure: Organize Angular into feature modules (e.g.,
user-module,product-module) with their own components, services, and templates. - Deployment:
- Single project: Build the Angular app with
ng build --prod(outputs toClientApp/dist), then publish the .NET Core project withdotnet publish --configuration Release. - Separate projects: Publish the API to a server, deploy the Angular app to a static file host (like Nginx) or Azure Static Web Apps, and ensure CORS is configured correctly.
- Single project: Build the Angular app with
内容的提问来源于stack exchange,提问作者Abhijit Mondal Abhi

