Add a WYSIWYG editor to ASP.NET Core
Turn a Razor Pages or MVC textarea into a rich text editor with image upload: tag helpers, an antiforgery header, two minimal API endpoints and HtmlSanitizer.
Step 1: Load the editor
Add the stylesheet and script to _Layout.cshtml. With LibMan or npm, copy the files to wwwroot/lib/wds-editor and link them from there.
<head>
...
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/wds-editor@1/dist/wds-editor.min.css" />
<script src="https://cdn.jsdelivr.net/npm/wds-editor@1/dist/wds-editor.min.js"></script>
</head>
Step 2: Turn the textarea into an editor
asp-for gives the textarea the property name as its id, and the editor keeps it in sync, so model binding works as before. The file manager sends the antiforgery token in the RequestVerificationToken header.
@page
@model CreateModel
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery
<form method="post">
<textarea asp-for="Body"></textarea>
<button type="submit">Save</button>
</form>
@section Scripts {
<script>
WDSEditor.init({
selector: '#Body',
preset: 'standard',
height: 480,
fileManager: {
listUrl: '/files/list',
uploadUrl: '/files/upload',
headers: { 'RequestVerificationToken': '@Antiforgery.GetAndStoreTokens(HttpContext).RequestToken' }
}
});
</script>
}
Step 3: Add the file manager endpoints
Two minimal API endpoints for signed-in users. Form uploads are checked by the antiforgery middleware, and files in wwwroot/uploads are served by UseStaticFiles (MapStaticAssets, used since .NET 9, only serves files that existed at build time). The full example with folders, rename and delete is on GitHub.
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseStaticFiles(); // serves wwwroot/uploads
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery(); // checks the token on form uploads
var uploads = Path.Combine(app.Environment.WebRootPath, "uploads");
Directory.CreateDirectory(uploads);
string[] allowed = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".pdf"];
var files = app.MapGroup("/files").RequireAuthorization();
files.MapGet("/list", () => Results.Json(new
{
files = new DirectoryInfo(uploads).EnumerateFiles()
.Where(f => allowed.Contains(f.Extension.ToLowerInvariant()))
.OrderByDescending(f => f.LastWriteTimeUtc)
.Select(f => new { url = "/uploads/" + f.Name, name = f.Name, size = f.Length })
}));
files.MapPost("/upload", async (IFormFile file) =>
{
var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowed.Contains(ext) || file.Length > 10 * 1024 * 1024)
return Results.Json(new { error = "Images or PDF files up to 10 MB." }, statusCode: 400);
var name = $"{Guid.NewGuid():N}{ext}";
await using var stream = File.Create(Path.Combine(uploads, name));
await file.CopyToAsync(stream);
return Results.Json(new { url = "/uploads/" + name, name });
});
app.MapRazorPages();
app.Run();
Step 4: Clean the HTML when you save
dotnet add package HtmlSanitizer installs a well-tested sanitizer. It keeps safe inline styles by default; allow class if you use the snippet library. Show the saved HTML with @Html.Raw(Model.Post.Body).
using Ganss.Xss;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class CreateModel(AppDbContext db) : PageModel
{
private static readonly HtmlSanitizer Sanitizer = CreateSanitizer();
[BindProperty]
public string Body { get; set; } = "";
public async Task<IActionResult> OnPostAsync()
{
db.Posts.Add(new Post { Body = Sanitizer.Sanitize(Body) });
await db.SaveChangesAsync();
return RedirectToPage("Index");
}
private static HtmlSanitizer CreateSanitizer()
{
var sanitizer = new HtmlSanitizer();
sanitizer.AllowedAttributes.Add("class"); // snippet library blocks
sanitizer.AllowDataAttributes = true; // checklists and @mentions
return sanitizer;
}
}
Good to know
- MVC: the same view code works with
asp-forin a controller view; validate the token with[ValidateAntiForgeryToken]as usual. - Blazor Server: call
WDSEditor.initfromOnAfterRenderAsyncthroughIJSRuntimeand read the HTML witheditor.getHTML(). - Large posts: raise
FormOptions.ValueLengthLimitif your HTML can be longer than 4 MB. - Every option, the toolbar items and the file manager JSON format are in the documentation; the server examples add folders, rename, delete and an AI endpoint.
FAQ
Is there a NuGet package for WDS Editor?
Not needed. The editor is a JavaScript file and a stylesheet, from the CDN or copied to wwwroot. The file manager needs the two minimal API endpoints shown above, or the full example from GitHub.
Why does the upload return 400 Bad Request in ASP.NET Core?
Usually the antiforgery token is missing. Inject IAntiforgery in the page and pass the request token in the RequestVerificationToken header of the fileManager options, as in step 2.
Why are uploaded images not shown in .NET 9 or later?
MapStaticAssets only serves files that existed when the app was built. Keep app.UseStaticFiles() for wwwroot/uploads, or store uploads in blob storage and return that URL.
Guides for other frameworks
Try WDS Editor in your browser
Free and MIT licensed, with a file manager, tables, Markdown and code blocks built in. No key, no account, no load limits.