Angular 2的HTML5 pushState在ASP.NET Core上的解决思路
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上的解决思路的更多相关文章
- asp.net core上使用Redis探索(2)
在<<asp.net core上使用Redis探索(1)>>中,我介绍了一个微软官方实现Microsoft.Extensions.Caching.Redis的类库,这次,我们使 ...
- 在ASP.NET Core上实施每个租户策略的数据库
在ASP.NET Core上实施每个租户策略的数据库 不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址 本博文翻译自: http://g ...
- asp.net core上使用Redis demo
整体思路:(1.面向接口编程 2.Redis可视化操作IDE 3.Redis服务) [无私分享:ASP.NET CORE 项目实战(第十一章)]Asp.net Core 缓存 MemoryCache ...
- 使用Code First建模自引用关系笔记 asp.net core上使用redis探索(1) asp.net mvc控制器激活全分析 语言入门必学的基础知识你还记得么? 反射
使用Code First建模自引用关系笔记 原文链接 一.Has方法: A.HasRequired(a => a.B); HasOptional:前者包含后者一个实例或者为null HasR ...
- [.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢?
[.NET Core]ASP.NET Core中如何解决接收表单时的不支持的媒体类型(HTTP 415 Unsupported Media Type)错误呢? 在ASP.NET Core应用程序中,接 ...
- 使用VS Code开发asp.net core (上)
本文是基于Windows10的. 下载地址: https://code.visualstudio.com/ insider 版下载地址: https://code.visualstudio.com/i ...
- ASP.NET Core 上传多文件 超简单教程
示例源码下载地址 https://qcloud.coding.net/api/project/3915794/files/4463836/download 项目地址 https://dev.tence ...
- ASP.NET Core 3.0 解决无法将“Add-Migration”项识别为 cmdlet、函数、脚本文件或可运行程序的名称错误
写在前面 在 ASP.NET Core 的项目中 使用 CodeFirst 的模式,进行初始化迁移时.出现如图所示的问题: 在度娘哪里查了半天之后,才从这个帖子里找到了答案.传送门 分析原因 ASP. ...
- asp.net core 上使用redis探索(3)--redis示例demo
由于是基于.net-core平台,所以,我们最好是基于IDistributedCache接口来实现.ASP.NET-CORE下的官方redis客户端实现是基于StackExchange的.但是官方提供 ...
随机推荐
- PMP 项目管理第六版- 组织治理与项目治理之间的关系
组织治理: 1.组织治理通过制定政策和流程,用结构化方式指明工作方向并进行控制,以便实现战略和运营目标. 2,组织治理通常由董事会执行,以确保对相关方的最终责任得以落实,并保持公平和透明. 项目治理: ...
- SQL Server Try Catch 异常捕捉
SQL Server Try Catch 异常捕捉 背景 今天遇到一个关于try catch 使用比较有意思的问题.如下一段代码: SELECT @@TRANCOUNT AS A BEGIN TRY ...
- linux-scp命令及如何设置免密登录
部署测试环境时经常在两台服务器间copy文件,那么如何设置免密登录? 场景:源服务器A(如172) -> 目标服务器B(如71) 实现将服务器A的文件copy到服务器B 实现方式有两种: 在源 ...
- UI测试之元素定位
定位方式优先级选择: ID>Name>CSS>XPath 1.使用id定位 2.使用name定位 3.使用class定位 4.使用css选择器定位 示例xml: <?xml ...
- httprunner-1-linux下搭建hrun(上)
前言 相信不少小伙伴对开源项目 httprunner 都很感兴趣,我们来看下它的有哪些特点吧: 项目管理:新增项目.列表展示及相关操作,支持用例批量上传(标准化的HttpRunner json和yam ...
- ASP.NET Core中的配置
配置 参考文件点击跳转 配置来源 命令行参数 自定义提供程序 目录文件 环境变量 内存中的.NET 对象 文件 默认配置 CreateDefaultBuilder方法提供有默认配置,在这个方法中会接收 ...
- CSS 阴影动画优化技巧一则
本技巧来自这篇文章 -- How to animate box-shadow with silky smooth performance 本文不是直译,因为觉得这个技巧很有意思很有用,遂起一文. bo ...
- Spring Cloud - Eureka /actuator/info 如何显示信息
在pom.xml中添加 <!-- actuator监控信息完善 --> <dependency> <groupId>org.springframework.boot ...
- JVM学习记录1--JVM内存布局
先上个图 这是根据<Java虚拟机规范(第二版)>所画的jvm内存模型. 程序计数器:程序计数器是用来记录当前线程方法执行顺序的,对应的就是我们编程中一行行代码的执行顺序,如分支,跳转,循 ...
- 封装自己通用的 增删改查的方法 By EF
封装自己的通用CURD By EF using System; using System.Collections.Generic; using System.Data.Entity; using Sy ...