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. Vue-cli中的跳转

    Vue-cli中的跳转 一.页面中跳转指定网页 写法一: <router-link :to="{name:'home'}"> 这里的name是在VUE路由里面的 写法二 ...

  2. 第3章(2) Linux下C编程风格

    Linux内核编码风格在内核源代码的Documentation/CodingStyle目录下(新版本内核在Documentation/process/coding-style.rst). 变量命名采用 ...

  3. Flash安全总结

    ActionScript AS是基于ECMAScript的语言,为了交互的需要flash应用引入ActionScript.ActionScript一共有三个版本,其中3.0较之前两个版本变化很大.Ac ...

  4. php 安装vld扩展

    下载地址 : http://pecl.php.net/package/vld 此处包是 : vld-0.14.0.tgz 1. tar -xvf  vld-0.14.0.tgz  -C  INSTAL ...

  5. luogu P4035 [JSOI2008]球形空间产生器

    [返回模拟退火略解] 题目描述 今有 n+1n+1n+1 个 nnn 维的点,它们都在一个球上.求它们所在球的球心. Solution 4035\text{Solution 4035}Solution ...

  6. php反序列化漏洞复现

    超适合小白的php反序列化漏洞复现 写在前头的话 在OWASP TOP10中,反序列化已经榜上有名,但是究竟什么是反序列化,我觉得应该进下心来好好思考下.我觉得学习的时候,所有的问题都应该问3个问题: ...

  7. 测试中常用sql

    1.增删改查 2.同一服务器下,要从一个数据库复制某张表到另一个数据库 create table test.sf_audit_plan as select * from v3_0_sf_full.sf ...

  8. git clone下代码window与unix换行问题

    项目中避免不了会写一些shell脚本,使用ln软连接到一个目录.当git clone到windows中,ln连接显示无比怪异(如../xx),打开.sh文件后(仅仅是打开了),git status会看 ...

  9. 06 python学习笔记-常用模块(六)

    一.  模块.包 1.什么是模块? Python 模块(Module),是一个 Python 文件,以 .py 结尾,包含了 Python 对象定义和Python语句,是用来组织代码的.模块能定义函数 ...

  10. 在.net core3.0中使用SignalR实现实时通信

    最近用.net core3.0重构网站,老大想做个站内信功能,就是有些耗时的后台任务的结果需要推送给用户.一开始我想简单点,客户端每隔1分钟调用一下我的接口,看看是不是有新消息,有的话就告诉用户有新推 ...