c# - 对象不是响应消息模型的原语

标签 c# asp.net asp.net-mvc swagger swashbuckle

我装饰了一个 Action 如下

[SwaggerResponse(HttpStatusCode.OK, "List of customers", typeof(List<CustomerDto>))]
[SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(NotFoundException))]

OK 模型正确显示。

但是,在 Repsonse 消息下,对于 NotFound,我得到“Object is not a primitive”。自定义异常派生自 Exception,实现了 ISerializable 并且还具有 [Serializable][DataContract()]

如何显示实际数据类型而不是消息?

此外,如果我使用此类属性装饰所有操作,在正常使用 WebApi 时是否会导致性能下降?

最佳答案

怎么样:

    [SwaggerResponse(HttpStatusCode.OK, "List of customers", typeof(IEnumerable<int>))]
    [SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(BadRequestErrorMessageResult))]
    [SwaggerResponse(HttpStatusCode.NotFound, Type = typeof(NotFoundResult))]
    public IHttpActionResult GetById(int id)
    {
        if (id > 0)
            return Ok(new int[] { 1, 2 });
        else if (id == 0)
            return NotFound();
        else
            return BadRequest("id must be greater than 0");
    }

http://swashbuckletest.azurewebsites.net/swagger/ui/index#!/IHttpActionResult/IHttpActionResult_GetById

关于c# - 对象不是响应消息模型的原语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41908889/

相关文章:

c# - 坚持在 C#/XNA 游戏中创建撤消功能

c# - 查找属于同一泛型类的所有属性

c# - ASP.NET Core Serilog 未将属性推送到其自定义列

c# - 如何遍历所有模型显示(名称=)属性值

c# - 使用 C# 读取 json 值而不使用属性

asp.net - 如何使用 "first-child"将 css 规则应用于表列的所有单元格?

c# - WebResource 是空白页

c# - 将页码添加到 Pdf 文档

asp.net-mvc - ASP.NET MVC 中有没有办法处理不同的 Response.StatusCode 值?

c# - 如何在 C# 中使用 StreamReader 从特定位置读取文件?