> 文档中心 > AspNetCore开源中间件-VueRouterHistory

AspNetCore开源中间件-VueRouterHistory


前言

用过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

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

除了 mod_rewrite,你也可以使用 FallbackResource。

nginx

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

原生 Node.js

const http = require('http')const fs = require('fs')const httpPort = 80http.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 文件,内容如下:

                                                

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。