你现在是一名aspnet网页的开发人员想要解决建立http服务器和get请求返回json响应的代码问题
建立HTTP服务器的代码可以使用ASP.NET的内置类HttpListener来实现。以下是一个简单示例:
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端口并接收GET请求。如果收到GET请求,它将返回一个JSON响应,其中包含一个名为“message”的属性,并将其值设置为“Hello, world!”。响应的Content-Type设置为“application/json”。
请注意,此示例仅用于演示目的。在实际应用程序中,您需要进行更多的错误处理和安全性检查
原文地址: http://www.cveoy.top/t/topic/cdbC 著作权归作者所有。请勿转载和采集!