Hey Guys
I am using ASP.Net Core to build a REST Api. We are enforcing https on our production server but not on develop. Is it possible to change the schema so that if env.IsProduction it uses https calls and if env.IsDevelopment it will use http calls?
Thanks for answering my question
If you are looking for a quick solution to this issue you can leverage our Swashbuckle extension package.
if (env.IsDevelopment()){
options.UseSchemes(schemes => schemes.Add("http"));
} else {
options.UseSchemes(schemes => schemes.Add("https"));
}
This is open source so feel free to copy past library code if you don't want to reference the library ^^.
@Franklin89 - by default Swashbuckle omits the "schemes" field in the Swagger output. This means that the swagger-ui tool will construct requests based on the scheme that was used to access the Swagger JSON. So, if you access the swagger-ui over HTTP in development, then that's what will be used to construct requests. And, if you access the swagger-ui over HTTPS in prod, then that will be used to construct requests. So, if I'm understanding your requirements correctly, this should just work correctly in both cases.
However, if you do want to specify an explicit scheme for each environment, you can use @sandorfr's extension OR you can leverage a simple hook to add the environment specific schemes prior to serializing the Swagger document into JSON:
app.UseSwagger(c =>
{
var schemes = _hostingEnv.IsDevelopment() ? new[] { "http" } : new[] { "https" };
c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Schemes = schemes);
});
Most helpful comment
@Franklin89 - by default Swashbuckle omits the "schemes" field in the Swagger output. This means that the swagger-ui tool will construct requests based on the scheme that was used to access the Swagger JSON. So, if you access the swagger-ui over HTTP in development, then that's what will be used to construct requests. And, if you access the swagger-ui over HTTPS in prod, then that will be used to construct requests. So, if I'm understanding your requirements correctly, this should just work correctly in both cases.
However, if you do want to specify an explicit scheme for each environment, you can use @sandorfr's extension OR you can leverage a simple hook to add the environment specific schemes prior to serializing the Swagger document into JSON: