Nswag: Add header into parameter (ASP.NET Web API)

Created on 1 Apr 2018  路  9Comments  路  Source: RicoSuter/NSwag

Just moved my swagger dependency to NSwag. It's great, however, there is no way to add a header (e.g X-Auth-User) as parameter for ASP.NETin Swagger UI. As FromHeader only available for ASP.NET Core, what's the way to display header param?

I tried custom FromHeaderAttribute but it fails.
public IHttpActionResult PostAuthentication([FromHeader("X-Auth-User")] string username)

in Swashbuckle, it can use IOperationFilter and

 operation.parameters.Add(new Parameter
                {
                    name = "X-Auth-User",
                    @in = "header",
                    type = "string",
                    required = true
                });
bug

Most helpful comment

Thanks. It works.

                context.OperationDescription.Operation.Parameters.Add(new SwaggerParameter
                {
                    Name = "X-Auth-User",
                    Kind = SwaggerParameterKind.Header,
                    Type = NJsonSchema.JsonObjectType.String,
                    IsRequired = true
                     });

All 9 comments

I will add support for FromHeaderAttribute soon...

For now you can implement a custom operation processor (see wiki, same as operation filter in Swashbuckle).

Thanks. It works.

                context.OperationDescription.Operation.Parameters.Add(new SwaggerParameter
                {
                    Name = "X-Auth-User",
                    Kind = SwaggerParameterKind.Header,
                    Type = NJsonSchema.JsonObjectType.String,
                    IsRequired = true
                     });

Very strange, it should be working out-of-the-box:

https://github.com/RSuter/NSwag/blob/master/src/NSwag.SwaggerGeneration.WebApi/Processors/OperationParameterProcessor.cs#L53

Do you use another namespace or do you see a problem?

Unfortunately, my project uses the obsolete ASP.NET, not ASP.NET Core which is not covered.

Ah ok. So this is not a bug. What you can do is implement an own attribute in the exact same namespace and name so that is detected by NSwag... but it may confuse other devs because it would not work for the ASP.NET (not Core) Web API model binder...

Hey @RicoSuter! I was wondering if there is a way to add a header to specific endpoints. I did what @ubeyou suggested and it worked. The only problem is the header value becomes mandatory for all endpoints.

Same as shaunwoolies, I also have an API with 5 business endpoints and 2 health check endpoints 'live' and 'ready', I want to mandate header for 5 business endpoints but exempt these 2 endpoints, how do I do that?

The ability to add a header info per route as needed would be awesome.

Was this page helpful?
0 / 5 - 0 ratings