AspNetCore开源中间件-VueRouterHistory
阅读原文时间:2022年05月11日阅读:1

前言

用过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 /)。

<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

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


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,请考虑使用 connect-history-api-fallback 中间件 。

安装 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>


rewrite {
    regexp .*
    to {path} /
}

在你的 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是实现原生AspNetCore下支持VueRouterhistory模式的中间件。

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

使用方法

  1. 通过nuget安装VueRouterHistory

    Install-Package VueRouterHistory -Version 1.0.2

  2. 注册中间件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。