一个网站如何挣钱,花钱做网站不给源码,全国购网站建设,票务网站建设目录
需求
文本编码检测
Markdown→HTML
注意
实现 需求
Markdown是一种文本格式#xff1b;不被浏览器支持#xff1b;编写一个在服务器端把Markdown转换为HTML的中间件。我们开发的中间件是构建在ASP.NET Core内置的StaticFiles中间件之上#xff0c;并且在它之前运…目录
需求
文本编码检测
Markdown→HTML
注意
实现 需求
Markdown是一种文本格式不被浏览器支持编写一个在服务器端把Markdown转换为HTML的中间件。我们开发的中间件是构建在ASP.NET Core内置的StaticFiles中间件之上并且在它之前运行所有的*.md文件都被放到wwwroot文件夹下当我们请求wwwroot下其他的静态文件的时候StaticFiles中间件会把它们返回给浏览器而当我们请求wwwroot下的*.md文件的时候我们编写的中间件会读取对应的*.md文件并且把它们转换为HTML格式返回给浏览器。
文本编码检测
NugetInstall-Package UTF.Unknown
DetectionResult result CharsetDetector.DetectFromStream(stream);
string charset result.Detected.EncodingName
CharsetDetector/UTF-unknown: Character set detector build in C# - .NET 5, .NET Core 2, .NET standard 1 .NET 4https://github.com/CharsetDetector/UTF-unknownhttps://github.com/CharsetDetector/UTF-unknownhttps://github.com/CharsetDetector/UTF-unknownhttps://github.com/CharsetDetector/UTF-unknown
Markdown→HTML
NugetInstall-Package MarkdownSharp
Markdown markdown new Markdown();
string html markdown.Transform(mdText);
注意
app.UseMiddlewareMarkdownMiddleware();需在app.UseStaticFiles();之前注册如果先注册了静态文件中间件那么所有对静态文件的请求都会直接由静态文件中间件处理而不会经过你的自定义中间件。
app.UseMiddlewareMarkdownMiddleware();
//配置服务器为静态文件提供服务
app.UseStaticFiles();
实现
public class MarkdownMiddleware
{private readonly RequestDelegate _next;private readonly IWebHostEnvironment hostEnv;public MarkdownMiddleware(RequestDelegate next, IWebHostEnvironment hostEnv){_next next;this.hostEnv hostEnv;}public async Task InvokeAsync(HttpContext context){//获取请求路径var path context.Request.Path.Value;//判断请求路径是否以.md结尾if (!path.EndsWith(.md, true, null)){await _next(context);return;}//判断请求路径是否存在var file hostEnv.WebRootFileProvider.GetFileInfo(path);if (!file.Exists){await _next(context);return;}//读取文件流using var stream file.CreateReadStream();//UTF.Unknown检测文件编码,获取检测结果DetectionResult result CharsetDetector.DetectFromStream(stream);string charset result.Detected.EncodingName ?? UTF-8;//流的位置重置stream.Position 0;//读取文件内容,并指定编码using StreamReader reader new StreamReader(stream, Encoding.GetEncoding(charset));string mdText await reader.ReadToEndAsync();//将Markdown转换为HTMLMarkdown markdown new Markdown();string html markdown.Transform(mdText);//设置响应头context.Response.ContentType text/html;charsetUTF-8;await context.Response.WriteAsync(html);}
}