Instantly share code, notes, and snippets.

Embed
What would you like to do?
Adding swagger to asp.net web.api 2 owin
public class AuthTokenDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
swaggerDoc.paths.Add("/token", new PathItem
{
post = new Operation
{
tags = new List<string> { "Auth" },
consumes = new List<string>
{
"application/x-www-form-urlencoded"
},
parameters = new List<Parameter> {
new Parameter
{
type = "string",
name = "grant_type",
required = true,
@in = "formData",
@default = "password"
},
new Parameter
{
type = "string",
name = "username",
required = false,
@in = "formData"
},
new Parameter
{
type = "string",
name = "password",
required = false,
@in = "formData"
}
}
}
});
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
SwaggerConfig.Register(config);
app.UseWebApi(config);
}
}
public class SwaggerConfig
{
public static void Register(HttpConfiguration httpConfig)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
httpConfig
.EnableSwagger(c =>
{
// API version definition
c.SingleApiVersion("v1", "AspNetWebAPIOauth2");
// Token
c.ApiKey("Token")
.Description("Bearer token")
.Name("Authorization")
.In("header");
c.DocumentFilter<AuthTokenDocumentFilter>();
})
.EnableSwaggerUi(c =>
{
// If your API supports ApiKey, you can override the default values.
// "apiKeyIn" can either be "query" or "header"
//
c.EnableApiKeySupport("Authorization", "header");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment