基于HttpStatusCode的不同响应模型示例

时间:2016-03-21 10:36:22

标签: c# swashbuckle

我有什么:

我有一个API,其中所有非成功响应返回" IApiException"

public class ApiException : Exception, IApiException
{
    public ExceptionType Type { get; set; }
    public int ErrorCode { get; set; }
    public HttpStatusCode Status { get; set; }
    public string Code { get; set; }
    public List<Error> Errors { get; set; } = new List<Error>();

    public ApiException(ExceptionType type, Reason reason, string message, HttpStatusCode httpStatus)
    {
        Type = type;
        Errors.Add(new Error { Message = message, Reason = reason.ToString() });
        Status = httpStatus;
        Code = httpStatus.ToString();
    }
}

如果我通过ISchemaFilter在swashbuckle中设置示例 它会在所有模型示例中使用相同的示例,因此401将返回与429相同的示例。

我想要的是什么:

我希望能够根据状态代码返回不同的示例。

我曾经尝试过:

我尝试创建IOperationsFilter,查找响应键,然后设置响应模式示例或响应示例。 但它根本没有显示模型。

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{

    foreach (var response in operation.responses)
    {

        if (response.Key == "401")
        {

            response.Value.description = "Error";                  
            response.Value.schema.example = new
            {
                Type = ExceptionType.Error.ToString(),
                Errors = new {Message = "Unauthorized", Reason = Reason.Unauthorized},
                Status = HttpStatusCode.Unauthorized,
                Code = HttpStatusCode.Unauthorized.ToString()
            };
        }
    }
}

enter image description here

0 个答案:

没有答案