You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于.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.

整合方式选择:单个项目 vs 分开项目

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:

  1. Right-click the Controllers folder → Add → Controller → Select "API Controller - Empty" → Name it ValuesController.
  2. 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:

  1. In your project root, run:
    ng new ClientApp --style css --routing false
    
    This creates an Angular 4 app in the ClientApp folder.
  2. Configure .NET Core to serve the Angular app:
    • Open Startup.cs and update the ConfigureServices method 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 Configure method 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");
              }
          });
      }
      
  3. Update Angular to call your API:
    • Open ClientApp/src/app/app.component.ts and 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.html to display the data:
      <h1>{{title}}</h1>
      <ul>
        <li *ngFor="let value of values">{{value}}</li>
      </ul>
      

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:

  1. Create the Web API project:

    dotnet new webapi -n MyApi
    cd MyApi
    

    Add CORS support in Startup.cs to 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();
    }
    
  2. Create the MVC project (optional, if you still need server-side views):

    dotnet new mvc -n MyMvc
    

    Or skip the MVC project and just use Angular as your frontend.

  3. Create the Angular 4 project:

    ng new MyAngularFrontend --style css --routing false
    

    Update the API call in Angular to use the API's full URL (e.g., http://localhost:5000/api/values).

项目规划 Tips
  • 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 to ClientApp/dist), then publish the .NET Core project with dotnet 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.

内容的提问来源于stack exchange,提问作者Abhijit Mondal Abhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:52:37