我们在 说到了HTTP请求的URL查询参数,这一节我们讲解一下在ASP.NET Core中如何优雅的拼接字符串,来提升我们代码的可读性。我们在这里会用到一个QueryString对象,这是一个C#中的结构体类型。
var app = WebApplication.Create();
app.Run(async context =>
{
var dicts = new Dictionary<string, string>()
{
["001", ] =
["桂兵兵", ] =
["1986/08/30", ] =
[ ] = Guid.NewGuid().ToString(),
["Bill Gui", ] =
["10 * 5 = 50" ] =
};
var queryString = QueryString.Create(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>使用 QueryString.Create 创建编码的URL查询字符串</h1>
<strong>Input</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(queryString.Value);
await context.Response.WriteAsync("</ul>");
await context.Response.WriteAsync(@"</div></body></html>");
});
app.Run();
从运行效果看,我们看到QueryString.Create方法创建是经过编码之后的URL。