Angular 2的HTML5 pushState在ASP.NET Core上的解决思路

正如Angular 2在Routing & Navigation中所提及的那样,Angular 2是推荐使用HTML5 pushState的URL style的。

localhost:3002/crisis-center/

而不是Angular 1中所使用的“hash URL sytle“

localhost:3002/src/#/crisis-center/

这种URL Style带来的问题是,直接输入的URL会直接访问对应Server资源,换言之,要支持这种URL Style,Server端必须增加额外的Routing才行。本文简单介绍一下在ASP.NET Core上的三种解决思路。

  • 解决思路一,使用NotFound的MiddleWare
    MSDN 有一篇Article介绍了如何实现自己的MiddleWare来实现自定义404 Page,当然,该Article主要Focus在如何智能纠错。我们这里只关注如何使用类似的方法来达到所需要的效果。

MiddleWare的实现代码:

    public class NotFoundMiddleware
{
private readonly RequestDelegate _next; public NotFoundMiddleware(RequestDelegate next)
{
_next = next;
} public async Task Invoke(HttpContext httpContext)
{
string path = httpContext.Request.Path; await _next(httpContext); if (httpContext.Response.StatusCode == 404 &&
(path.StartsWith("/allowpath1")
|| path.StartsWith("/allowpath2"))
{
string indexPath = "wwwroot/index.html";
// Redirect is another way
//httpContext.Response.Redirect(indexPath, permanent: true);
httpContext.Response.Clear();
httpContext.Response.StatusCode = 200; // HttpStatusCode.OK;
httpContext.Response.ContentType = "text/html"; await httpContext.Response.WriteAsync(File.ReadAllText(indexPath));
}
}
} // Extension method used to add the middleware to the HTTP request pipeline.
public static class NotFoundMiddlewareExtensions
{
public static IApplicationBuilder UseNotFoundMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<NotFoundMiddleware>();
}
}

然后再Startup Class中使用该MiddleWare:

app.UseNotFoundMiddleware();
  • 解决思路二,使用Routing
    使用Routing是另外一种解决问题的思路,即把所有默认的request发送给默认的Controller。这里,要求启用标准的MVC。
    实现一个HomeController类:
    public class HomeController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
}

创建Index.cshtml,必须放置在Views\Home或者Views\Shared文件夹中,文件内容即index.html内容。
然后再Startup 类中指定default routing:

        public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//services.AddMvcCore()
// .AddJsonFormatters();
} public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(); if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute("AngularDeepLinkingRoute", "{*url}",
new { controller = "Home", action = "Index" });
});
}

值得注意的是,必须在project.json中把Views文件夹加入publishOptions的include部分:

  "publishOptions": {
"include": [
"wwwroot",
"Views",
"web.config",
],
"exclude": [
"node_modules",
"bower_components"
]
},
  • 解决思路三,直接修改Request的Path
    这个思路更加简单暴力,也更为高效,因为之前的思路要么是访问失败(404的StatusCode)后的Redirect,要么是路由失败后的Default实现,这个思路直接在Request入口就改写了Request的Path
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler(); var angularRoutes = new[] {
"/allowpath1",
"/allowpath2",
}; app.Use(async (context, next) =>
{
if (context.Request.Path.HasValue &&
null !=
angularRoutes.FirstOrDefault(
(ar) => context.Request.Path.Value.StartsWith(ar, StringComparison.OrdinalIgnoreCase)))
{
context.Request.Path = new PathString("/");
} await next();
}); app.UseDefaultFiles();
app.UseStaticFiles();
}

是为之记。
Alva Chien
2016.8.24

Angular 2的HTML5 pushState在ASP.NET Core上的解决思路的更多相关文章

  1. asp.net core上使用Redis探索(2)

    在<<asp.net core上使用Redis探索(1)>>中,我介绍了一个微软官方实现Microsoft.Extensions.Caching.Redis的类库,这次,我们使 ...

  2. 在ASP.NET Core上实施每个租户策略的数据库

    在ASP.NET Core上实施每个租户策略的数据库 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://g ...

  3. asp.net core上使用Redis demo

    整体思路:(1.面向接口编程 2.Redis可视化操作IDE 3.Redis服务) [无私分享:ASP.NET CORE 项目实战(第十一章)]Asp.net Core 缓存 MemoryCache ...

  4. 使用Code First建模自引用关系笔记 asp.net core上使用redis探索(1) asp.net mvc控制器激活全分析 语言入门必学的基础知识你还记得么? 反射

    使用Code First建模自引用关系笔记   原文链接 一.Has方法: A.HasRequired(a => a.B); HasOptional:前者包含后者一个实例或者为null HasR ...

  5. [.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢?

    [.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢? 在ASP.NET Core应用程序中,接 ...

  6. 使用VS Code开发asp.net core (上)

    本文是基于Windows10的. 下载地址: https://code.visualstudio.com/ insider 版下载地址: https://code.visualstudio.com/i ...

  7. ASP.NET Core 上传多文件 超简单教程

    示例源码下载地址 https://qcloud.coding.net/api/project/3915794/files/4463836/download 项目地址 https://dev.tence ...

  8. ASP.NET Core 3.0 解决无法将“Add-Migration”项识别为 cmdlet、函数、脚本文件或可运行程序的名称错误

    写在前面 在 ASP.NET Core 的项目中 使用 CodeFirst 的模式,进行初始化迁移时.出现如图所示的问题: 在度娘哪里查了半天之后,才从这个帖子里找到了答案.传送门 分析原因 ASP. ...

  9. asp.net core 上使用redis探索(3)--redis示例demo

    由于是基于.net-core平台,所以,我们最好是基于IDistributedCache接口来实现.ASP.NET-CORE下的官方redis客户端实现是基于StackExchange的.但是官方提供 ...

随机推荐

  1. PHP 插入排序 -- 直接插入排序

    1)直接插入序 -- Straight Insertion Sort 时间复杂度 :O(n^2) 适用条件: 适合记录数不多的情况 1 <?php 2 $a = [0 =>3,4,5,1, ...

  2. [BZOJ29957] 楼房重建 - 线段树

    2957: 楼房重建 Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 3294  Solved: 1554[Submit][Status][Discus ...

  3. Vue项目多域名跨域

    在Vue项目中请求后台数据时,遇到的多域名跨域问题. 直接上代码: assetsSubDirectory: "static", assetsPublicPath: "/& ...

  4. POI读入Excel用String读取数值类型失真问题(精度丢失)

    问题:POI读取Excel数值单元格时,读取的小数数值与真实值不一致 话不多说,直接上代码! public static String getRealStringValue(Cell cell) { ...

  5. ESP8266开发之旅 网络篇③ Soft-AP——ESP8266WiFiAP库的使用

    1. 前言     在前面的篇章中,博主给大家讲解了ESP8266的软硬件配置以及基本功能使用,目的就是想让大家有个初步认识.并且,博主一直重点强调 ESP8266 WiFi模块有三种工作模式: St ...

  6. instruments无法连接,设备查询不到,找不到工程,查询不到对应app

    这种问题真是让人捉急,一定要沐浴更衣,怀着一颗虔诚的心. 1.拔掉设备(iPhone/iPad),关掉设备.(长按电源键) 2.关闭Xcode和Instruments 3.重启设备(iPhone/iP ...

  7. java Int数据工具类

    1.在使用tcp协议传输数据时,使用到的 Int 数据的工具类方法 //将 Int 数据转换成字节数组 public static byte[] intToByteArray(int data){ b ...

  8. JAVA aio简单使用

    使用aio,实现客户端和服务器 对一个数进行轮流累加 //服务器端 public class Server { private static ExecutorService executorServi ...

  9. SpringData-Redis发布订阅自动重连分析

    SpringData-Redis发布订阅自动重连分析 RedisMessageListenerContainer 配置 @Bean @Autowired RedisMessageListenerCon ...

  10. 彻底理解Python多线程中的setDaemon与join【配有GIF示意】

    在进行Python多线程编程时, join() 和 setDaemon() 是最常用的方法,下面说说两者的用法和区别. 1.join () 例子:主线程A中,创建了子线程B,并且在主线程A中调用了B. ...