• AspNetCore开源中间件-VueRouterHistory


    VueRouterHistory

    Nuget

    用于Vue单页面应用,使用VueRouter的History模式下,通过AspNetCore提供文件服务。

    前言

    用过VueRouter路由组件的应该都知道,VueRouterhashhistory两种模式。hash模式会在url中插入#history模式下url则看上去更加简洁美观。如果想要支持history模式则必须要后端服务进行配合。

    常用后端服务器配置方式请参考 后端配置例子

    后端配置例子

    注意:下列示例假设你在根目录服务这个应用。如果想部署到一个子目录,你需要使用 Vue CLI 的 publicPath 选项 (opens new window)和相关的 router base property (opens new window)。你还需要把下列示例中的根目录调整成为子目录 (例如用 RewriteBase /name-of-your-subfolder/ 替换掉 RewriteBase /)。

    Apache

    <IfModule mod_rewrite.c>
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /index.html [L]
    </IfModule>
    

    除了 mod_rewrite,你也可以使用 FallbackResource

    nginx

    location / {
      try_files $uri $uri/ /index.html;
    }
    

    原生 Node.js

    const http = require('http')
    const fs = require('fs')
    const httpPort = 80
    
    http.createServer((req, res) => {
      fs.readFile('index.html', 'utf-8', (err, content) => {
        if (err) {
          console.log('We cannot open "index.html" file.')
        }
    
        res.writeHead(200, {
          'Content-Type': 'text/html; charset=utf-8'
        })
    
        res.end(content)
      })
    }).listen(httpPort, () => {
      console.log('Server listening on: http://localhost:%s', httpPort)
    })
    

    基于 Node.js 的 Express

    对于 Node.js/Express,请考虑使用 connect-history-api-fallback 中间件 。

    Internet Information Services (IIS)

    安装 IIS UrlRewrite

    在你的网站根目录中创建一个 web.config 文件,内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
      <system.webServer>
        <rewrite>
          <rules>
            <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
              <match url="(.*)" />
              <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
              </conditions>
              <action type="Rewrite" url="/" />
            </rule>
          </rules>
        </rewrite>
      </system.webServer>
    </configuration>
    

    Caddy

    rewrite {
        regexp .*
        to {path} /
    }
    

    Firebase 主机

    在你的 firebase.json 中加入:

    {
      "hosting": {
        "public": "dist",
        "rewrites": [
          {
            "source": "**",
            "destination": "/index.html"
          }
        ]
      }
    }
    

    警告

    给个警告,因为这么做以后,你的服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,你应该在 Vue 应用里面覆盖所有的路由情况,然后再给出一个 404 页面。

    const router = new VueRouter({
      mode: 'history',
      routes: [
        { path: '*', component: NotFoundComponent }
      ]
    })
    

    或者,如果你使用 Node.js 服务器,你可以用服务端路由匹配到来的 URL,并在没有匹配到路由的时候返回 404,以实现回退。更多详情请查阅 Vue 服务端渲染文档 (opens new window)。

    原生AspNetCore实现

    现如今AspNetCore完全不需要依赖IIS即可进行部署,如何在AspNetCore原生应用中进行支持VueRouterhistory想必是很多人遇到到的问题之一,也许大部分人选择使用hash模式,因为它虽然丑点,但是不需要任何配置即可使用。
    为了带给像我一样强烈需要history模式的用户,索性写了个中间件,经过测试,能够完美支持VueRouter组件history模式的部署。

    VueRouterHistory

    VueRouterHistory是实现原生AspNetCore下支持VueRouterhistory模式的中间件。

    源码已开源在Github: https://github.com/SpringHgui/VueRouterHistory

    使用方法

    1. 通过nuget安装VueRouterHistory
    Install-Package VueRouterHistory -Version 1.0.2
    
    1. 注册中间件app.UseVueRouterHistory()

    app.UseRouting()app.MapControllers()之后添加app.UseVueRouterHistory();

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
    
        app.UseStaticFiles();
    
        app.UseRouting();
        
        // ==============添加这一行即可================
        app.UseVueRouterHistory();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    
    1. 将Vue编译后的产物全部放置到wwwroot文件夹下
    2. 开始体验你的应用吧~

    结语

    VueRouterHistory中间件的使用,让我们免于对iis进行配置以实现history模式部署,使项目不管是托管在IIS还是直接自托管模式,都不需要进行额外的配置。
    欢迎有需要的朋友通过VueRouterHistory包进行支持history模式,如遇到问题,请提交ISSU。


    __EOF__

  • 本文作者: Gui.H
  • 本文链接: https://www.cnblogs.com/springhgui/p/16251477.html
  • 关于博主: 评论和私信会在第一时间回复。或者直接私信我。
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
  • 声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。
  • 相关阅读:
    原码、反码、补码相关知识
    vivo霍金实验平台设计与实践-平台产品系列02
    首个落地实践!曙光存储案例入选液冷数据中心白皮书
    奇舞周刊第507期:通过 View Transition API 在状态之间添加丰富的过渡动画
    树莓派 qt 调用multimedia、multimediawidgets、serialport、Qchats
    类和对象(1)
    解决java.lang.ClassNotFoundException: org.junit.platform.launcher.TestIdentifier
    实习记录(一):MySQL时间偏差问题的发现与解决
    证件照dpi怎么调高?修改图片分辨率的快捷方式
    计算机毕业设计springboot+vue+elementUI高考填报志愿综合参考系统
  • 原文地址:https://www.cnblogs.com/springhgui/p/16251477.html