Skip to main content
 首页 » 编程设计

c#之在 webapi 中设置状态代码和内容

2024年01月31日28telwanggs

我想通过设置状态代码获得一个漂亮而简单的 API,并获得 swagger (swashbuckle) 的文档

首先,我的 Controller 是这样的:

public class ValuesController : ControllerBase 
{ 
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<Value>))] 
    [HttpGet, System.Web.Mvc.Route("api/values/")] 
    public async Task<List<Value>> GetValues(HttpRequestMessage request) 
    { 
        using (DatabaseContext context = new DatabaseContext()) 
        { 
            return await context.Values.Take(10).ToListAsync(); 
        } 
    } 
} 

一切正常,Swagger 显示 json 格式的结果。问题是,我无法设置状态代码(例如,如果数据库错误我可以设置为 Err 500 或 s.th.)。

Here我读到,为了设置状态代码,我们需要返回 HttpResponseMessage

所以我修改了我的代码:

public class ValuesController : ControllerBase 
{ 
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(HttpResponseMessage))] 
    [HttpGet, System.Web.Mvc.Route("api/values/")] 
    public async Task<HttpResponseMessage> GetValues(HttpRequestMessage request) 
    { 
        using (DatabaseContext context = new DatabaseContext()) 
        { 
            var valuesToReturn = await context.Values.Take(10).ToListAsync(); 
            return request.CreateResponse(HttpStatusCode.NotModified, valuesToReturn); 
        } 
    } 
} 

现在,状态代码设置正确,但 swagger 没有显示任何结果。

所以,我认为这可能是一个招摇的问题。

下一步是使用 Chromes Boomerang-Plugin 测试 API,但相同: Status-Code 为 304,但正文(结果/内容)为空:

肯定有结果:

知道如何使用 HttpResponseMessage 正确设置正文吗? 或者,当返回值为例如时,关于如何在 api 方法中设置状态代码的任何想法List<Value> ?

请您参考如下方法:

起初 HTTP 状态代码 304 没有body。 304 响应不得包含消息正文,因此始终以 header 字段后的第一个空行结束。

只需更改状态码即可。