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. Flask中多APP应用以及admin后台系统

    一.多APP from werkzeug.wsgi import DispatcherMiddleware from werkzeug.serving import run_simple from f ...

  2. ride工具使用

    1.新建project,suite, testcase (1) 新建project:file->new project  ,输入工程名,选择Type选directory,选择工程存放路径,ok ...

  3. PHP代码审计基础-初级篇

    对于php代码审计我也是从0开始学的,对学习过程进行整理输出沉淀如有不足欢迎提出共勉.对学习能力有较高要求,整个系列主要是在工作中快速精通php代码审计,整个学习周期5天 ,建议花一天时间熟悉php语 ...

  4. mongodb学习笔记系列一

    一.简介和安装 ./bin/mongod --dbpath /path/to/database --logpath /path/to/log --fork --port 27017 mongodb非常 ...

  5. vue实现简单学生信息管理案例

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. ios 11 系统CPU过高,xib中textfield使用导致出过高

    ios11 发布之后,作为开发肯定是第一时间进行了升级测试,全新的系统不免会带来这样那样的问题.项目中使用xib的小伙伴们会发现,项目的cpu使用率非常高,尤其是初始化的时候,并没有线程的操作,CPU ...

  7. float使用0xFF

    1. float f = 0xFFFFFFFF; 这一句完全是错误的用法,它不会使f变量内存变为4个0xFF,因为0xFFFFFFFF根本就不是有效的float数值,编译器无从处理,如果用printf ...

  8. 27 个问题突破所有重难点,BroadcastReceiver 、ContentProvider 知多少?「建议收藏」

    前言 距离上次更新过去一周多了,打破了之前两到三天一更的惯例,主要还是这部分内容太多了. 原先想把 BroadcastReceiver .ContentProvider 分两篇来总结,但的确,这两大组 ...

  9. 学习笔记36_Razor

    *Razor视图引擎 在添加视图的时候,视图引擎除了有“aspx”外,还有Razor(CSHTML),就会在对应的文件夹下,产生 view.cshtml文件,那么,以后写C#代码,就可以 @for(v ...

  10. 监控tomcat,自动启动

    tomcatID=`ps -ef |grep tomcat |grep -v 'grep'|awk '{print $2}'`  tomcatCount=`ps -ef|grep tomcat |gr ...