在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):RickStrahl/Westwind.AspNetCore.Markdown开源软件地址(OpenSource Url):https://github.com/RickStrahl/Westwind.AspNetCore.Markdown开源编程语言(OpenSource Language):C# 46.1%开源软件介绍(OpenSource Introduction):ASP.NET Core Markdown SupportThis small package provides Markdown support for your ASP.NET Core applications. It has the following features:
Related links: Installing the NuGet PackageYou can install the package from NuGet in Visual Studio or from the command line: PM> install-package westwind.aspnetcore.markdown or the dotnet add package westwind.aspnetcore.markdown Startup ConfigurationTo use these components you need to add the following to your Startup class at minimum. The following is for ASP.NET Core 3.0 and later using endpoint routing: public void ConfigureServices(IServiceCollection services)
{
services.AddMarkdown();
// We need to use MVC so we can use a Razor Configuration Template
services.AddMvc()
// have to let MVC know we have a controller
.AddApplicationPart(typeof(MarkdownPageProcessorMiddleware).Assembly);
}
public void Configure(IApplicationBuilder app)
{
// if you use default files make sure you do it before markdown middleware
app.UseDefaultFiles(new DefaultFilesOptions()
{
DefaultFileNames = new List<string> { "index.md", "index.html" }
});
app.UseMarkdown();
app.UseStaticFiles();
// the following enables MVC and Razor Pages
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// endpoints.MapRazorPages(); // optional
// MVC routing is required
endpoints.MapDefaultControllerRoute();
});
} There are additional configuration options for the
Markdown Parsing HelpersAt it's simplest this component provides Markdown parsing that you can use to convert Markdown text to HTML either inside of application code, or inside of Razor expressions. Markdown to Stringstring html = Markdown.Parse(markdownText); Markdown to Razor Html String<div>@Markdown.ParseHtmlString(Model.ProductInfoMarkdown)</div> Parse Markdown to String from a FileYou can also convert Markdown using a file: var html = Markdown.ParseFromFile("~/EmbeddedMarkdownContent.md");
// async
html = await Markdown.ParseFromFileAsync("~/EmbeddedMarkdownContent.md"); To embed in Razor Views: @Markdown.ParseHtmlStringFromFile("~/EmbeddedMarkdownContent.md") Parse Markdown to String from a UrlYou can also load Markdown from a URL as long as it's openly accessible via a URL: // sync
parsedHtml = Markdown.ParseFromUrl("https://github.com/RickStrahl/Westwind.AspNetCore.Markdown/raw/master/readme.md")
// async
parsedHtml = await Markdown.ParseFromUrlAsync("https://github.com/RickStrahl/Westwind.AspNetCore.Markdown/raw/master/readme.md"); HtmlString versions are also available of this method. SanitizeHtml in Parser Methods to mitigate XSSBoth of the above methods include a few optional parameters including a string html = Markdown.Parse(markdownText, sanitizeHtml: true) MarkDig Pipeline ConfigurationThis component uses the MarkDig Markdown Parser which allows for explicit feature configuration via many of its built-in extensions. The default configuration enables the most commonly used Markdown features and defaults to Github Flavored Markdown for most settings. If you need to customize what features are supported you can override the pipeline creation explicitly in the services.AddMarkdown(config =>
{
// Create custom MarkdigPipeline
// using MarkDig; for extension methods
config.ConfigureMarkdigPipeline = builder =>
{
builder.UseEmphasisExtras(Markdig.Extensions.EmphasisExtras.EmphasisExtraOptions.Default)
.UsePipeTables()
.UseGridTables()
.UseAutoIdentifiers(AutoIdentifierOptions.GitHub) // Headers get id="name"
.UseAutoLinks() // URLs are parsed into anchors
.UseAbbreviations()
.UseYamlFrontMatter()
.UseEmojiAndSmiley(true)
.UseListExtras()
.UseFigures()
.UseTaskLists()
.UseCustomContainers()
.UseGenericAttributes();
//.DisableHtml(); // don't render HTML - encode as text
};
}); When set this configuration is used every time the Markdown parser instance is created instead of the default behavior. Markdown TagHelperThe Markdown TagHelper allows you to embed static Markdown content into a To get started with the Markdown TagHelper you need to do the following:
After installing the NuGet package you have to register the tag helper so MVC can find it. The easiest way to do this is to add it to the @addTagHelper *, Westwind.AspNetCore.Markdown Literal Markdown ContentTo use the literal content control you can simply place your Markdown text between the opening and closing <markdown>
#### This is Markdown text inside of a Markdown block
* Item 1
* Item 2
### Dynamic Data is supported:
The current Time is: @DateTime.Now.ToString("HH:mm:ss")
```cs
// this c# is a code block
for (int i = 0; i < lines.Length; i++)
{
line1 = lines[i];
if (!string.IsNullOrEmpty(line1))
break;
}
```
</markdown> The TagHelper turns the Markdown text into HTML, in place of the TagHelper content.
TagHelper AttributesfilenameYou can specify a filename to pull Markdown from and render into HTML. Files can be referenced:
urlYou can also load Markdown documents from URL and process them as markdown to HTML for embedding into the page. The Url has to be openly accessible (ie. no authentication). This is great for loading and embedding content from remote sources such as from Github and rendering it as part of your application. It's very useful for CMS and Documentation solutions where a remote repository serves as the document store. url-fixup-basepathWhen markdown (Model Binding)In addition to the content you can also bind to the @model MarkdownPageModel
@{
Model.MarkdownText = "This is some **Markdown**!";
}
<markdown markdown="Model.MarkdownText" /> The normalize-whitespaceMarkdown is sensitive to leading spaces and given that you're likely to enter Markdown into the literal TagHelper in a code editor there's likely to be a leading block of white space. Markdown treats leading white space as significant - 4 spaces or a tab indicate a code block so if you have: <markdown>
#### This is Markdown text inside of a Markdown block
* Item 1
* Item 2
### Dynamic Data is supported:
The current Time is: @DateTime.Now.ToString("HH:mm:ss")
</markdown> without special handling Markdown would interpret the entire markdown text as a single code block. By default the TagHelper sets Optionally you can also force justify your code and turn the setting to <markdown normalize-whitespace="false">
#### This is Markdown text inside of a Markdown block
* Item 1
* Item 2
### Dynamic Data is supported:
The current Time is: @DateTime.Now.ToString("HH:mm:ss")
</markdown> This also works, but is hard to maintain in some code editors due to auto-code reformatting. sanitize-htmlBy default the Markdown tag helper strips The default behavior strips the script content shown below ( <markdown sanitize-html="true">
### Rudimentary XSS Support
Below are a script tag, and some raw HTML alert with an onclick handler which
are potential XSS vulnerable. Default is `strip-script-tags="true"` to remove
script and other vulnerabilities.
<a href="javascript: alert('Gotcha! javascript: executed.');">Malicious Link</a>
<script>
alert("GOTHCHA! Injected code executed.")
</script>
<div class="alert alert-info" onmouseover="alert('Gotcha! onclick handler fired');">
XSS Alert: You shouldn't be able to click me and execute the onclick handler.
</div>
</markdown> With the flag set to no-http-exceptionOptional parameter that can be set if you are using a URL bound to the tag helper. When Markdown Page Processor MiddlewareThe Markdown middleware allows you drop To use this feature you need to do the following:
Note that the default template location can be customized for each folder and it can live anywhere including the Startup ConfigurationAs with any middleware components you need to configure the Markdown middleware and hook it up for processing which is a two step process. First you need to call At it's simplest you can just do: public void ConfigureServices(IServiceCollection services)
{
services.AddMarkdown(config =>
{
// just add a folder as is
config.AddMarkdownProcessingFolder("/docs/");
services.AddMvc();
}
} This configures the Markdown processor for default behavior which handles All of these values can be customized with additional configuration options in services.AddMarkdown(config =>
{
// optional Tag BlackList
config.HtmlTagBlackList = "script|iframe|object|embed|form"; // default
// Simplest: Use all default settings
var folderConfig = config.AddMarkdownProcessingFolder("/docs/", "~/Pages/__MarkdownPageTemplate.cshtml");
// Customized Configuration: Set FolderConfiguration options
folderConfig = config.AddMarkdownProcessingFolder("/posts/", "~/Pages/__MarkdownPageTemplate.cshtml");
// Optionally strip script/iframe/form/object/embed tags ++
folderConfig.SanitizeHtml = false; // default
// folderConfig.BasePath = "http://othersite.com";
// Optional configuration settings
folderConfig.ProcessExtensionlessUrls = true; // default
folderConfig.ProcessMdFiles = true; // default
// Optional pre-processing - with filled model
folderConfig.PreProcess = (model, controller) =>
{
// controller.ViewBag.Model = new MyCustomModel();
};
// optional custom MarkdigPipeline (using MarkDig; for extension methods)
config.ConfigureMarkdigPipeline = builder =>
{
builder.UseEmphasisExtras(Markdig.Extensions.EmphasisExtras.EmphasisExtraOptions.Default)
.UsePipeTables()
.UseGridTables()
.UseAutoIdentifiers(AutoIdentifierOptions.GitHub) // Headers get id="name"
.UseAutoLinks() // URLs are parsed into anchors
.UseAbbreviations()
.UseYamlFrontMatter()
.UseEmojiAndSmiley(true)
.UseListExtras()
.UseFigures()
.UseTaskLists()
.UseCustomContainers()
//.DisableHtml() // renders HTML tags as text including script
.UseGenericAttributes();
};
}); There are additional options including the ability to hook in a pre-processor that's fired on every controller hit. In the example I set a custom model to the ViewBag that the template can potentially pick up and work with. For applications you might have a stock View model that provides access rights and other user logic that needs to fire to access the page and display the view. Using the In addition to the configuration you also need to hook up the Middleware in the public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseMarkdown();
app.UseStaticFiles();
app.UseMvc();
} The Note that both Create a Markdown Page View TemplateMarkdown is just an HTML fragment, not a complete document, so a host template is required into which the rendered Markdown is embedded. To accomplish this the middleware uses a well-known MVC controller endpoint that loads the configured Razor view template that embeds the Markdown text. The middleware reads in the Markdown file from disk, and then uses a generic MVC controller method call the specified template to render the page containing your Markdown text as the content. The template is passed a Typically the template page is pretty simple and only contains the rendered Markdown plus a reference to a The actual rendered Markdown content renders into HTML is pushed into the page via A minimal template page can do something like this: @model Westwind.AspNetCore.Markdown.MarkdownModel
@{
ViewBag.Title = Model.Title;
Layout = "_Layout";
}
<div style="margin-top: 40px;">
@Model.RenderedMarkdown
</div> This template can be a self contained file, or as I am doing here, it can reference a A more complete template might also add a code highlighter (highlightJs here) and custom styling something more along the lines of this: @model Westwind.AspNetCore.Markdown.MarkdownModel
@{
Layout = "_Layout";
}
@section Headers {
@if (!string.IsNullOrEmpty(Model.BasePath))
{
<base href="@Model.BasePath" />
}
<style>
h3 {
margin-top: 50px;
padding-bottom: 10px;
border-bottom: 1px solid #eee;
}
/* vs2015 theme specific*/
pre {
background: #1E1E1E;
color: #eee;
padding: 0.7em !important;
overflow-x: auto;
white-space: pre;
word-break: normal;
word-wrap: normal;
}
pre > code {
white-space |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论