为任何api方法中未使用的类型添加类型定义

时间:2017-01-19 13:22:21

标签: asp.net-web-api2 swagger swagger-ui swashbuckle

我有一个带有自定义标头的api端点。 此标头是一个如下所示的对象:

User: {"UserId":"someguid"}

如果我在api方法中将类型作为参数,我可以执行以下操作:

public class AddFileParamTypes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.operationId == "FileDelivery_Post")
        {

            operation.consumes.Add("multipart/form-data");
            operation.parameters.Add(new Parameter
            {
                name = "file",
                required = true,
                type = "file",
                @in = "formData"
            });
            operation.parameters.Add(new Parameter
            {
                name = "User",
                required = true,
                schema = new Schema() { @ref = "#/definitions/User" },
                @in = "header"
            });
        }
    }
}

但用户类型不是方法的参数,那么如何将定义添加到swashbuckle?

1 个答案:

答案 0 :(得分:0)

发现,它很简单,但缺乏文档:

public class AddFileParamTypes : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.operationId == "FileDelivery_Post")
        {

            operation.consumes.Add("multipart/form-data");
            operation.parameters.Add(new Parameter
            {
                name = "file",
                required = true,
                type = "file",
                @in = "formData"
            });
            operation.parameters.Add(new Parameter
            {
                name = "User",
                required = true,
                schema = schemaRegistry.GetOrRegister(typeof(User)),
                @in = "header"
            });
        }
    }
}