ASP.NET Core 知识速递 - Day 5:每天进步一点

文摘   2024-09-20 08:00   日本  

《ASP.NET Core 知识速递 - Day 3:每天进步一点 文章中我们讲解了如何更优雅的方式创建编码的url查询字符串,在这节中我们我们使用System.Net.Http.FormUrlEncodedContent类对name/values进行编码并生成一个查询字符串的url,使用的application/x-www-form-urlencoded MIME 类型。

使用ASP.NET Core Empty的项目模板创建一个空的项目:
var app = WebApplication.Create();app.Run(async context =>{    var dicts = new Dictionary<string, string>()    {        ["id"] = "001",        ["name"] = "gui bingbing",        ["birthday"] = "1986/08/30",        ["guid"] = Guid.NewGuid().ToString(),        ["artist"] = "Bill Gui",        ["formula"] = "10 * 5 = 50"    };    using var queryString = new FormUrlEncodedContent(dicts);    context.Response.Headers.Append("Content-Type", "text/html;charset=utf-8");    await context.Response.WriteAsync($@"<html>    <head>        <link rel=""stylesheet"" href=""https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.css"" />    </head>    <body class=""content"">    <div class=""container"">    <h1>使用 FormUrlEncodedContent 创建编码的URL字符串</h1>    <strong>输入</strong>    ");    await context.Response.WriteAsync("<ul>");    foreach (var k in dicts)    {        await context.Response.WriteAsync($"<li>{k.Key} = {k.Value}</li>");    }    await context.Response.WriteAsync("</ul>");    await context.Response.WriteAsync("<strong>输出</strong><br/>");    await context.Response.WriteAsync(await queryString.ReadAsStringAsync());    await context.Response.WriteAsync("</ul>");    await context.Response.WriteAsync(@"</div></body></html>");});app.Run();

运行应用程序:

源代码地址:
https://github.com/bingbing-gui/AspNetCore-Skill/tree/master/src/aspnetcore-knowledge-point/form-url-encoded-content

桂迹
分享原创,记录痕迹!
 最新文章