【Vue】Vue与ASP.NET Core WebAPI的集成

SPA单页面应用已经遍地开花,熟知的三大框架,AngularVueReact,其中AngularReact均可集成至ASP.NET Core,且提供了相关了中间件。但是Vue没有:

As far as I’m aware, we don’t have plans to introduce Vue-specific features. This isn’t because we have anything against Vue, but rather just to limit the growth in the number of frameworks that we’re maintaining support for. The dev team only has a finite capacity for handling third-party concepts, and last year we made the strategic choice to focus on only Angular and React.

本篇将介绍如何集成Vue

1.集成的效果

SPAASP.NET Core集成后。可以达到两种不同效果

1.1 一键开启

通过Vistual Studio-->F5,便可以直接启动前端应用和后台服务,可在用一个端口下调试运行。这种方便单人开发调试。

1.2 分开运行,无需修改代理

常用调试方式启动后端api服务,记住端口号(假设后端端口-3000),然后去前端配置文件,如vue.config.js修改代理

module.exports = {
    //omit some config..
    devServer: {
        proxy: 'localhost:3000'
    }
}

但是集成后,就不必这样操作,只需要在后端UseProxyToSpaDevelopmentServer中指定固定的SPA调试服务器地址。这种除了适用单人开发外,还适合前端部署部署完成,单独调试后端接口问题。

2.集成的原理

2.1 启动前端

通过中间件调用node服务,执行如下命令

npm start -- --port {dynamic_port}
  • dynamic_port是在运行过程中随机一个端口。npm 命令已经存在在 package.json 中配置,它将通过 vue-cli-service serve --port 启动开发服务器。

2.2 代理前端调试服务器

前端调试服务器启动成功后,中间件将会创建一个HttpClient代理:将请求一起转发到前端调试服务器 ,然后将响应复制为自己的响应。

3.集成步骤

3.1 安装nuget包

Install-Package Garfield.SpaServices.Extensions.Vue -Version 1.0.0

这是博主根据官方库改写,正如nuget包的文档写点那样:由于官方没有支持Vue,看后续是否支持,如支持,此包将归档废弃。

3.2 创建Vue项目

在API项目创建ClientApp文件,在此文件夹下创建或复制Vue项目。

保证以下目录结构即可:

ClientApp/package.json

3.3 修改package.json

"scripts": {
    "start": "vue-cli-service serve --port", //edit here
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "test:unit": "vue-cli-service test:unit",
    "test:e2e": "vue-cli-service test:e2e"
},

3.4 修改Startup.cs

//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    //omit some code..
    services.AddSpaStaticFiles(c=>
                               {
                                   c.RootPath = "ClientApp/dist";
                               });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //omit some code..
    app.UseStaticFiles();
    
    //PRODUCTION uses webpack static files
    if (!env.IsDevelopment())
    {
        app.UseSpaStaticFiles();
    }
    app.UseSpa(spa =>
               {
                   spa.Options.SourcePath = "ClientApp";

                   if (env.IsDevelopment())
                   {
                       spa.UseVueCliServer(npmScript: "start");
                       //spa.UseProxyToSpaDevelopmentServer("http://localhost:8080");
                   }
               });
}

4.还原构建-Build

在我们调试之前,一定是构建项目,但是我们的项目现在是一个包含前端Vue后端Webapi的前后端分离项目。后端需要还原各种nuget包,在那之前,前端也需要还原npm包,以前博主是执行npm install

这里介绍下使用MSBuild自动执行,修改csproj,增加Target:

<PropertyGroup>
    <!--omit some-->
    <SpaRoot>ClientApp</SpaRoot>
</PropertyGroup>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
    <!-- Ensure Node.js is installed -->
    <Exec Command="node --version" ContinueOnError="true">
        <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
    </Exec>
    <Error Condition="'$(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." />
    <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
</Target>

此时就会优先在Build ASP.NET WebAPI项目前,还原前端项目。

5.调试-Debug

5.1 集成调试

保持上面的配置与代码不变,直接运行ASP.NET Web API

Vue将会自动构建,并与ASP.NET Core WebAPI项目将会集成运行,通过访问localhost:port便可以访问应用。

5.2 独立调试

如果后端接口稳定,仅仅是前端问题,那么上面的集成调试时比较方便的。但是如果是前端稳定,后端接口修改频繁,那么这样的方式无疑是太慢了,因为每次都需要重新构建vue项目。所以独立调试后端更符合此类场景.

5.2.1 启动前端

cd ClientApp
npm start 8080

5.2.2 修改后端

// spa.UseVueCliServer(npmScript: "start"); //替换如下代码
spa.UseProxyToSpaDevelopmentServer("http://localhost:8080");

当启动 ASP.NET Core 应用时,它不会启动 Vue dev 服务器, 而是使用手动启动的实例。 这使它能够更快地启动和重新启动。 不再需要每次都等待 Vue CLI 重新生成客户端应用。

6.发布-Publish

以往博主部署这种前后端分离项目,是通过nginx部署静态前端文件,反向代理后端接口。这种方式没问题。但是这里介绍一点新鲜的(至少对博主而言),前端Vue项目通过npm run build构建成一系列的静态文件。这些静态文件就是我们的SPA。说白了,就是一个静态网页。

所以需要静态文件中间件:

app.UseStaticFiles();
if (!env.IsDevelopment())
{
    app.UseSpaStaticFiles();
}

最重要的是发布时随着WebAPI一起发布,而不需要,单独执行npm run build然后手动拷贝,这里还是用到了MSbuild,所以同样需要修改csproj文件,增加publishTarget

  <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <!--<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />-->
    <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />
    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
      <DistFiles Include="$(SpaRoot)dist**; $(SpaRoot)dist-server**" />
      <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
        <RelativePath>%(DistFiles.Identity)</RelativePath>
        <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
        <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>

这时再通过Visual Studio后者命令发布时,就会同步构建前端项目,发布后端API且包含前端构建后的dist文件.现在就可以不用分开部署。

参考链接

https://docs.microsoft.com/zh-cn/visualstudio/msbuild/msbuild-well-known-item-metadata?view=vs-2019

https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/visual-studio-publish-profiles?view=aspnetcore-3.1

https://docs.microsoft.com/zh-cn/visualstudio/msbuild/msbuild?view=vs-2019

https://blog.csdn.net/sinat_36112136/article/details/103039817

https://github.com/dotnet/sdk/issues/795#issuecomment-289782712

原文地址:https://www.cnblogs.com/RandyField/p/13850027.html