欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > Markdown转换器中间件

Markdown转换器中间件

2025/2/5 15:31:38 来源:https://blog.csdn.net/Anoxia_li/article/details/145434411  浏览:    关键词:Markdown转换器中间件

目录

需求

文本编码检测

Markdown→HTML

注意

实现


需求

  1. Markdown是一种文本格式;不被浏览器支持;编写一个在服务器端把Markdown转换为HTML的中间件。
  2. 我们开发的中间件是构建在ASP.NET Core内置的StaticFiles中间件之上,并且在它之前运行,所有的*.md文件都被放到wwwroot文件夹下,当我们请求wwwroot下其他的静态文件的时候,StaticFiles中间件会把它们返回给浏览器,而当我们请求wwwroot下的*.md文件的时候,我们编写的中间件会读取对应的*.md文件并且把它们转换为HTML格式返回给浏览器。

文本编码检测

Nuget:Install-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 4+https://github.com/CharsetDetector/UTF-unknownhttps://github.com/CharsetDetector/UTF-unknown

Markdown→HTML

Nuget:Install-Package MarkdownSharp

Markdown markdown = new Markdown();
string html = markdown.Transform(mdText);

注意

app.UseMiddleware<MarkdownMiddleware>();需在app.UseStaticFiles();之前注册,如果先注册了静态文件中间件,那么所有对静态文件的请求都会直接由静态文件中间件处理,而不会经过你的自定义中间件。

app.UseMiddleware<MarkdownMiddleware>();
//配置服务器为静态文件提供服务
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;charset=UTF-8";await context.Response.WriteAsync(html);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com