ASP.NET 纯文本
最后修改于 2023 年 10 月 18 日
在本文中,我们将展示如何在 ASP.NET 应用程序中提供纯文本。
ASP.NET 是一个跨平台、高性能、开源的框架,用于构建现代、支持云的 Web 应用程序。它由 Microsoft 开发。
内容类型
内容类型,也称为媒体类型,是与文件一起发送的字符串,用于指示文件类型。它描述了内容的格式;例如,HTML 文件可能被标记为 text/html,或图像文件被标记为 image/png)。它与 Windows 上的文件名扩展名具有相同的作用。
content-type
标头值用于指示资源的媒体类型。text/plain; charset=utf-8
用于文本文件。
ASP.NET 纯文本示例
返回纯文本的最简单方法是使用 lambda 表达式。
$ dotnet new web --no-https -o PlainTextEx
我们创建一个新的 ASP.NET Web 应用程序。
Program.cs
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "home page\n"); app.MapGet("/about", () => Results.Content("about page\n")); app.MapGet("/contact", () => "contact page\n"); app.Run("https://:3000");
我们有三个映射。这些映射使用 lambda 表达式。
app.MapGet("/", () => "home page\n");
在第一个映射中,我们发送一个字符串。ASP.NET 会自动设置状态码和内容类型。
app.MapGet("/about", () => Results.Content("about page\n"));
我们还可以使用 Results.Content
辅助方法来实现更明确的意图。
$ dotnet watch
我们启动应用程序。
$ curl localhost:3000 -i HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Date: Tue, 27 Sep 2022 10:28:43 GMT Server: Kestrel Transfer-Encoding: chunked home page $ curl localhost:3000/about -i HTTP/1.1 200 OK Content-Length: 11 Content-Type: text/plain; charset=utf-8 Date: Tue, 27 Sep 2022 10:25:54 GMT Server: Kestrel about page $ curl localhost:3000/contact -i HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Date: Tue, 27 Sep 2022 10:29:00 GMT Server: Kestrel Transfer-Encoding: chunked contact page
我们使用 curl 创建 GET 请求。
ASP.NET 纯文本示例 II
在第二个示例中,我们从控制器返回纯文本响应。
Program.cs
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.Run("https://:3000");
在 Program.cs
中,我们设置了控制器。
Controllers/Home/HomeController.cs
using Microsoft.AspNetCore.Mvc; namespace PlainTextEx.Controllers; public class HomeController : Controller { [Produces("text/plain")] [HttpGet("/")] public IActionResult Home() { string msg = "home page\n"; return Ok(msg); } [HttpGet("about")] public ContentResult About() { return Content("about page\n"); } }
我们有两个操作方法。
[Produces("text/plain")] [HttpGet("/")] public IActionResult Home() { string msg = "home page\n"; return Ok(msg); }
使用 Produces
属性,我们设置了内容类型。我们将消息放入 Ok
方法中,该方法设置 OK 状态码。
[HttpGet("about")] public ContentResult About() { return Content("about page\n"); }
或者,我们也可以使用 ContentResult
和 Content
来生成纯文本响应。
$ curl localhost:3000 -i HTTP/1.1 200 OK Content-Type: text/plain; charset=utf-8 Date: Tue, 27 Sep 2022 10:22:49 GMT Server: Kestrel Transfer-Encoding: chunked home page
我们生成一个到主页的 GET 请求。
$ curl localhost:3000/about -i HTTP/1.1 200 OK Content-Length: 11 Content-Type: text/plain; charset=utf-8 Date: Tue, 27 Sep 2022 10:23:39 GMT Server: Kestrel about page
我们生成一个到关于页面的 GET 请求。
在本文中,我们展示了如何在 ASP.NET 应用程序中提供纯文本。