Skip to content

Commit

Permalink
示範 HtmlEncoder 與 JavaScriptEncoder 用法
Browse files Browse the repository at this point in the history
  • Loading branch information
doggy8088 committed Sep 1, 2023
1 parent 356d95c commit 08f14d8
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
2 changes: 2 additions & 0 deletions Controllers/HomeController.cs
Expand Up @@ -15,6 +15,8 @@ public HomeController(ILogger<HomeController> logger)

public IActionResult Index()
{
ViewBag.Message = "如何用 'ASP.NET Core' 打造 Web 應用程式";

return View();
}

Expand Down
7 changes: 7 additions & 0 deletions Program.cs
@@ -1,8 +1,15 @@
using System.Text.Encodings.Web;
using System.Text.Unicode;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddSingleton<HtmlEncoder>(
HtmlEncoder.Create(allowedRanges: new[] { UnicodeRanges.BasicLatin,
UnicodeRanges.CjkUnifiedIdeographs }));

var app = builder.Build();

// Configure the HTTP request pipeline.
Expand Down
8 changes: 6 additions & 2 deletions Views/Home/Index.cshtml
@@ -1,8 +1,12 @@
@{
ViewData["Title"] = "Home Page";
var jsEncoder = System.Text.Encodings.Web.JavaScriptEncoder.Default;
}

<script>
var str = '@Html.Raw(jsEncoder.Encode(ViewBag.Message))';
</script>

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<p>@ViewBag.Message</p>
</div>

0 comments on commit 08f14d8

Please sign in to comment.