Asp.net core中HttpResponse常用属性及Status code

发布时间 2023-10-11 12:44:38作者: JohnYang819

在ASP.NET Core中,HttpResponse 表示HTTP响应,其中包括一些常用的属性和方法,用于设置HTTP响应的各种属性。HTTP响应通常由一个HTTP状态码,HTTP头(headers),和HTTP主体(body)组成。以下是一些常用的 HttpResponse 属性和一些常见的HTTP状态码及其含义:

HttpResponse 常用属性:

StatusCode: 用于设置HTTP响应的状态码,如 200、404、500 等。

ContentType: 用于设置HTTP响应的内容类型(MIME类型),例如 "application/json"、"text/html"。

Headers: 用于添加或修改HTTP响应头信息,如设置响应的缓存策略、允许的跨域请求等。

Cookies: 用于操作响应中的HTTP cookies,包括添加、修改、删除等操作。

Body: 用于设置HTTP响应的主体内容。通常,您可以使用 response.WriteAsync() 方法来将内容写入响应主体。

常见的HTTP状态码及其含义:

200 OK: 请求成功。服务器已成功处理了请求。

201 Created: 已创建。服务器已成功创建了资源。

204 No Content: 无内容。服务器成功处理请求,但没有返回任何内容。

400 Bad Request: 请求无效。通常是因为请求参数或语法错误。

401 Unauthorized: 未授权。需要进行身份验证或授权才能访问资源。

403 Forbidden: 禁止访问。服务器理解请求,但拒绝提供服务。

404 Not Found: 未找到。请求的资源不存在。

500 Internal Server Error: 服务器内部错误。通常是服务器端代码错误导致的。

503 Service Unavailable: 服务不可用。服务器当前无法处理请求,通常是临时性的。

public static void Main(string[] args)
        {
            WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
            WebApplication app = builder.Build();
            ConcurrentDictionary<string, Fruit> _fruit = new ConcurrentDictionary<string, Fruit>();
            app.MapGet("/fruit", () => _fruit);
            app.MapGet("/fruit/{id}", (HttpResponse response,string id) =>
            {
                var ifSuccess=_fruit.TryGetValue(id, out var fruit);
                if (!ifSuccess)
                {
                    response.StatusCode = 404;
                    response.ContentType = MediaTypeNames.Text.Plain;
                    return response.WriteAsync($"没有发现id={id}的fruit");
                }
                string jsonFruit = JsonSerializer.Serialize(fruit, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
                response.StatusCode = 200;
                response.ContentType = MediaTypeNames.Application.Json;
                return response.WriteAsync(jsonFruit);

            });
            app.MapPost("/fruit/{id}", ( Fruit fruit,string id,HttpResponse response) =>
            {
                var ifSuccess = _fruit.TryAdd(id, fruit);
                if (!ifSuccess)
                {
                    response.StatusCode = 418;
                    response.ContentType=MediaTypeNames.Text.Plain;
                    return response.WriteAsync($"已存在id={id}的fruit");

                }
                response.StatusCode = 201;
                response.ContentType = MediaTypeNames.Text.Plain;
                return response.WriteAsync($"已存入");
            });
            app.Run();
        }

以及从以上代码可以看出:传入的参数顺序并不固定,可以string id,Fruit fruit,HttpResponse res,也可以Fruit fruit,HttpResponse res,string id.