繁体   English   中英

有没有办法用 .NET MVC 提供 vue.js statc 文件?

[英]Is there a way to serve vue.js statc file with .NET MVC?

我得到了一个由 vue-cli 生成的示例 vue 应用程序,它使用 npm 运行构建命令生成 static 文件。

通常,您使用 node.js 的服务器来提供文件,但我想知道是否有办法从我的 ASP.NET MVC 应用程序中提供这些文件。

我之所以这么问,是因为我需要展示 Vue.js 的工作原理,因为我们正在考虑从 Knockout.js 移开。

我找到了一个解决方案:

我们可以轻松使用使用 vue-cli 创建的任何示例 vue 应用程序。 因为这实际上是通过 HTTP 服务器提供 static 文件的问题,这将在 .NET MVC 中工作。

  1. 在项目中的任何位置创建您的 Vue 应用程序。 我个人建议您在 .net mvc 项目的根级别创建它。

  2. 添加一个 vue.config.js 文件并指定 publicPath,它将确定生成所有 static 文件的文件夹的路径。

  3. 添加一个 controller 来提供将由 vue 应用程序创建的 static 文件。

为获得最佳实践,请确保 controller 的名称与 publicPath 中指定的文件夹名称相同。

例子:

vue.config.js

module.export = {
  publicPath:'~/Dist'
}

public class DistController : Controller {

}
  1. 仅当您的应用程序中有 VUE 路由器时才适用:

对于您在 vue-router 中定义的每个路由,请确保您有一个与该路由的路径同名的 Action 方法。 每个方法都需要返回生成的 static html 或 cshtml 文件。

注意:对于您的主要组件,请确保您使用自定义路径名,即(不使用“/”)

例子:


const router = new VueRouter({
  routes: [
    { path: '/home', component: Home },
    { path: '/login', component: Login },
    { path: '/about', component: About }
  ]
})


public class DistController : Controller {

        public ActionResult home()
        {
          return new FilePathResult("~/Html/index.html", "text/html");
        }


        public ActionResult about()
        {
          return new FilePathResult("~/Html/index.html", "text/html");
        }

        public ActionResult login()
        {
           return new FilePathResult("~/Html/index.html", "text/html");
        }

  1. 构建您的生产项目:

在发表此评论时,您可以使用以下命令执行此操作:

npm run build

将生成包含所有 static 文件的文件夹。

ASP.NET 应用程序中的客户端路由

迟到的回应,但分享,因为简单的答案很难找到。 UseStaticFiles()的使用有据可查,并且适用于 SPA ,直到刷新页面或使用直接 url 访问应用程序。 要启用客户端路由,可以配置回退路径以将任何未解析的服务器端路由传递给客户端应用程序。

简要说明

假设您的 Vue 应用程序(或任何 SPA)被复制到名为wwwroot的根目录中:

在 Startup.cs 的 Configure() 中,添加UseDefaultFiles()UseStaticFiles()以便可以找到并提供index.html

支持客户端路由的关键是向UseEndpoints()添加一个回退端点。 任何未在服务器端处理的路由都将传递给客户端应用程序并成功路由。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  app.UseHttpsRedirection();

  // Important: UseDefaultFiles() before UseStaticFiles()
  app.UseDefaultFiles();
  app.UseStaticFiles();

  app.UseRouting();

  app.UseEndpoints(endpoints =>
  {
     endpoints.MapControllers();
     // Routing magic: Pass route to client app
     endpoints.MapFallbackToFile("/index.html");
  });
}

参考: https://weblog.west-wind.com/posts/2020/Jul/12/Handling-SPA-Fallback-Paths-in-a-Generic-ASPNET-Core-Server

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM