ASP.NET HttpListener: 如何建立 HTTP 服务器并返回 JSON 响应
使用 ASP.NET 的内置类 HttpListener 可以轻松创建 HTTP 服务器。以下示例展示了如何建立一个监听本地 8080 端口的 HTTP 服务器,并返回一个包含'message'属性的 JSON 响应。
using System;
using System.Net;
using System.IO;
using System.Text.Json;
class Program
{
static void Main(string[] args)
{
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("HTTP server started on http://localhost:8080/");
while (true)
{
var context = listener.GetContext();
var request = context.Request;
var response = context.Response;
if (request.HttpMethod == "GET")
{
response.ContentType = "application/json";
response.StatusCode = 200;
var json = new { message = "Hello, world!" };
var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(json);
response.ContentLength64 = jsonBytes.Length;
response.OutputStream.Write(jsonBytes, 0, jsonBytes.Length);
}
response.OutputStream.Close();
}
}
}
该代码将在本地 8080 端口启动一个 HTTP 服务器,监听 GET 请求。当收到 GET 请求时,它将返回一个 JSON 响应,包含一个名为'message'的属性,其值为'Hello, world!'。响应的 Content-Type 设置为'application/json'。
请注意,此示例仅用于演示目的。在实际应用中,您需要进行更全面的错误处理和安全性检查。
原文地址: https://www.cveoy.top/t/topic/nq71 著作权归作者所有。请勿转载和采集!