How to vary the required fields for POST and PUT in Swashbuckle?How to make HTTP POST web requestSimple post to Web ApiWhy not inherit from List<T>?Duplicate parameter output in SwaggerHow to query for metadata that is required for a put or a post?Custom Model Binder not invoking from Swagger UIHow to remove 'required' setting from form field using jQuery unobtrusive validationHow to exclude property from Swagger documentation on certain endpointsAspNetCore Swagger/Swashbuckle how to modify xml schema requestsIs it possible for Swagger to show a different model view for POST and PATCH, ie for write-once property?
Limits and Continuity in Multi variable calculus.
I think my ex-employer secretely kept me in their system as an employee
How to translate 脑袋短路 into English?
Gofer work in exchange for Letter of Recommendation
How can I train a replacement without letting my bosses and the replacement know?
Unity: transform.LookAt(target) not "looking at" target?
What happened after the end of the Truman Show?
What animal has fat with the highest energy density?
Interaction between Ethereal Absolution versus Edgar Markov with Captivating Vampire
Are there any OR challenges that are similar to kaggle's competitions?
Convert HTML color to OLE
Unbiased estimator of exponential of measure of a set?
"Silverware", "Tableware", and "Dishes"
Why should I pay for an SSL certificate?
Story about a demon trying to make a man insane
Cheap storage lockers in Tromsø, Norway
Why is su world executable?
E: Sub-process /usr/bin/dpkg returned an error code (1) - but how do I find the meaningful error messages in APT's output?
Why don't politicians push for fossil fuel reduction by pointing out their scarcity?
How do slats reduce stall speed?
Is it allowable to use an organization's name to publish a paper in a conference, even after I graduate from it?
Designing a prison for a telekinetic race
Default camera device to show screen instead of physical camera
TechSupport Issue ID#812
How to vary the required fields for POST and PUT in Swashbuckle?
How to make HTTP POST web requestSimple post to Web ApiWhy not inherit from List<T>?Duplicate parameter output in SwaggerHow to query for metadata that is required for a put or a post?Custom Model Binder not invoking from Swagger UIHow to remove 'required' setting from form field using jQuery unobtrusive validationHow to exclude property from Swagger documentation on certain endpointsAspNetCore Swagger/Swashbuckle how to modify xml schema requestsIs it possible for Swagger to show a different model view for POST and PATCH, ie for write-once property?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I'm responsible for maintaining the company API documentation. Our API is written ASP.NET. I recently switched to using Swashbuckle 5.6.0 which is working nicely.
The issue I've come accross is this:
We separate our data models into Post data and Get data, for example WebAccountGetData.cs
and WebAccountPostData.cs
. The Post data can be used when creating (POST) and updating (PUT).
Most, if not all, fields in the Post data classes are nullable, when an API method is called, the stored proc returns error messages describing what fields are missing/required. The API doesn't handle required fields.
Using nullable fields means Swashbuckle will not add a Required flag to the documentation. But we would like to show whether a field is required or not, based on the Http method used (Post/Put).
The API Key is a required parameter as it is not nullable.
I'm aware that I can use the [Required]
attribute from the System.ComponentModel.DataAnnotations namespace, but this will apply the Required flag to both the POST and PUT methods, which we do not want.
Idealy, I'd like to use a custom Attribute where I can specify whether a field is required in the Post or Put method.
public class ApiRequiredAttribute : Attribute
public bool RequiredInPost
get;
set;
= false;
public bool RequiredInPut
get;
set;
= false;
And then use it like so:
[ApiRequired(RequiredInPost = true)]
public int? ApprovalStatusId
get;
set;
Is there a way to use a custom IDocumentFilter
, IOperationFilter
or ISchemaFilter
to apply changes (like toggling the required flag) to the schema properties of a model field? Or is it not possible in Swashbuckle to reference Attributes on a model?
c# asp.net-web-api swashbuckle redoc
add a comment |
I'm responsible for maintaining the company API documentation. Our API is written ASP.NET. I recently switched to using Swashbuckle 5.6.0 which is working nicely.
The issue I've come accross is this:
We separate our data models into Post data and Get data, for example WebAccountGetData.cs
and WebAccountPostData.cs
. The Post data can be used when creating (POST) and updating (PUT).
Most, if not all, fields in the Post data classes are nullable, when an API method is called, the stored proc returns error messages describing what fields are missing/required. The API doesn't handle required fields.
Using nullable fields means Swashbuckle will not add a Required flag to the documentation. But we would like to show whether a field is required or not, based on the Http method used (Post/Put).
The API Key is a required parameter as it is not nullable.
I'm aware that I can use the [Required]
attribute from the System.ComponentModel.DataAnnotations namespace, but this will apply the Required flag to both the POST and PUT methods, which we do not want.
Idealy, I'd like to use a custom Attribute where I can specify whether a field is required in the Post or Put method.
public class ApiRequiredAttribute : Attribute
public bool RequiredInPost
get;
set;
= false;
public bool RequiredInPut
get;
set;
= false;
And then use it like so:
[ApiRequired(RequiredInPost = true)]
public int? ApprovalStatusId
get;
set;
Is there a way to use a custom IDocumentFilter
, IOperationFilter
or ISchemaFilter
to apply changes (like toggling the required flag) to the schema properties of a model field? Or is it not possible in Swashbuckle to reference Attributes on a model?
c# asp.net-web-api swashbuckle redoc
Yes you can use IDocumentFilter for that, give it a try and update this post if you get stuck
– Helder Sepulveda
Mar 29 at 2:00
add a comment |
I'm responsible for maintaining the company API documentation. Our API is written ASP.NET. I recently switched to using Swashbuckle 5.6.0 which is working nicely.
The issue I've come accross is this:
We separate our data models into Post data and Get data, for example WebAccountGetData.cs
and WebAccountPostData.cs
. The Post data can be used when creating (POST) and updating (PUT).
Most, if not all, fields in the Post data classes are nullable, when an API method is called, the stored proc returns error messages describing what fields are missing/required. The API doesn't handle required fields.
Using nullable fields means Swashbuckle will not add a Required flag to the documentation. But we would like to show whether a field is required or not, based on the Http method used (Post/Put).
The API Key is a required parameter as it is not nullable.
I'm aware that I can use the [Required]
attribute from the System.ComponentModel.DataAnnotations namespace, but this will apply the Required flag to both the POST and PUT methods, which we do not want.
Idealy, I'd like to use a custom Attribute where I can specify whether a field is required in the Post or Put method.
public class ApiRequiredAttribute : Attribute
public bool RequiredInPost
get;
set;
= false;
public bool RequiredInPut
get;
set;
= false;
And then use it like so:
[ApiRequired(RequiredInPost = true)]
public int? ApprovalStatusId
get;
set;
Is there a way to use a custom IDocumentFilter
, IOperationFilter
or ISchemaFilter
to apply changes (like toggling the required flag) to the schema properties of a model field? Or is it not possible in Swashbuckle to reference Attributes on a model?
c# asp.net-web-api swashbuckle redoc
I'm responsible for maintaining the company API documentation. Our API is written ASP.NET. I recently switched to using Swashbuckle 5.6.0 which is working nicely.
The issue I've come accross is this:
We separate our data models into Post data and Get data, for example WebAccountGetData.cs
and WebAccountPostData.cs
. The Post data can be used when creating (POST) and updating (PUT).
Most, if not all, fields in the Post data classes are nullable, when an API method is called, the stored proc returns error messages describing what fields are missing/required. The API doesn't handle required fields.
Using nullable fields means Swashbuckle will not add a Required flag to the documentation. But we would like to show whether a field is required or not, based on the Http method used (Post/Put).
The API Key is a required parameter as it is not nullable.
I'm aware that I can use the [Required]
attribute from the System.ComponentModel.DataAnnotations namespace, but this will apply the Required flag to both the POST and PUT methods, which we do not want.
Idealy, I'd like to use a custom Attribute where I can specify whether a field is required in the Post or Put method.
public class ApiRequiredAttribute : Attribute
public bool RequiredInPost
get;
set;
= false;
public bool RequiredInPut
get;
set;
= false;
And then use it like so:
[ApiRequired(RequiredInPost = true)]
public int? ApprovalStatusId
get;
set;
Is there a way to use a custom IDocumentFilter
, IOperationFilter
or ISchemaFilter
to apply changes (like toggling the required flag) to the schema properties of a model field? Or is it not possible in Swashbuckle to reference Attributes on a model?
c# asp.net-web-api swashbuckle redoc
c# asp.net-web-api swashbuckle redoc
edited Mar 27 at 19:07
Helen
38.3k5 gold badges92 silver badges149 bronze badges
38.3k5 gold badges92 silver badges149 bronze badges
asked Mar 27 at 14:39
Matt CleggMatt Clegg
933 silver badges13 bronze badges
933 silver badges13 bronze badges
Yes you can use IDocumentFilter for that, give it a try and update this post if you get stuck
– Helder Sepulveda
Mar 29 at 2:00
add a comment |
Yes you can use IDocumentFilter for that, give it a try and update this post if you get stuck
– Helder Sepulveda
Mar 29 at 2:00
Yes you can use IDocumentFilter for that, give it a try and update this post if you get stuck
– Helder Sepulveda
Mar 29 at 2:00
Yes you can use IDocumentFilter for that, give it a try and update this post if you get stuck
– Helder Sepulveda
Mar 29 at 2:00
add a comment |
1 Answer
1
active
oldest
votes
I've managed to find a solution!
I created an IOperationFilter
that creates new schemas for POST and PUT methods, based on properties with my custom ApiRequired
attribute (see original question).
internal class ApplyRequiredAttributeFilter : IOperationFilter
public void Apply( Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription )
HttpParameterBinding[] parameterBindings = apiDescription.ActionDescriptor.ActionBinding.ParameterBindings;
foreach ( HttpParameterBinding binding in parameterBindings )
PropertyInfo[] properties = binding.Descriptor.ParameterType.GetProperties();
// If the type is not an object and has no properties, ignore it.
if ( properties.Length == 0 )
continue;
Parameter modelParamater = operation.parameters.Last();
if ( modelParamater == null )
continue;
string schemaPath = modelParamater.schema?.@ref;
string schemaName = schemaPath?.Split( '/' ).Last();
if ( schemaName == null )
continue;
Schema oldSchema = schemaRegistry.Definitions[ schemaName ];
// Copy the existing schema.
Schema newSchema = new Schema
description = oldSchema.description,
properties = new Dictionary<string, Schema>( oldSchema.properties ),
required = oldSchema.required != null ? new List<string>( oldSchema.required ) : new List<string>(),
@type = oldSchema.type,
vendorExtensions = new Dictionary<string, object>( oldSchema.vendorExtensions )
;
// Find model properties with the custom attribute.
foreach ( PropertyInfo property in properties )
ApiRequiredAttribute attribute = property.GetCustomAttribute<ApiRequiredAttribute>();
if ( attribute != null )
I then add the filter to my EnableSwagger call.
GlobalConfiguration.Configuration
.EnableSwagger("docs/swagger/", c =>
// Other initialization code...
c.OperationFilter<ApplyRequiredAttributeFilter>();
);
The attributes are used like so:
[ApiRequired( RequiredInPost = true, RequiredInPut = true)]
public bool? Active
get;
set;
[ApiRequired( RequiredInPost = true )]
public string UserName
get;
set;
Finally, on the docs, the required flags look like this. The POST method parameters are on the left while the PUT method paramaters are on the right:
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55379920%2fhow-to-vary-the-required-fields-for-post-and-put-in-swashbuckle%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I've managed to find a solution!
I created an IOperationFilter
that creates new schemas for POST and PUT methods, based on properties with my custom ApiRequired
attribute (see original question).
internal class ApplyRequiredAttributeFilter : IOperationFilter
public void Apply( Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription )
HttpParameterBinding[] parameterBindings = apiDescription.ActionDescriptor.ActionBinding.ParameterBindings;
foreach ( HttpParameterBinding binding in parameterBindings )
PropertyInfo[] properties = binding.Descriptor.ParameterType.GetProperties();
// If the type is not an object and has no properties, ignore it.
if ( properties.Length == 0 )
continue;
Parameter modelParamater = operation.parameters.Last();
if ( modelParamater == null )
continue;
string schemaPath = modelParamater.schema?.@ref;
string schemaName = schemaPath?.Split( '/' ).Last();
if ( schemaName == null )
continue;
Schema oldSchema = schemaRegistry.Definitions[ schemaName ];
// Copy the existing schema.
Schema newSchema = new Schema
description = oldSchema.description,
properties = new Dictionary<string, Schema>( oldSchema.properties ),
required = oldSchema.required != null ? new List<string>( oldSchema.required ) : new List<string>(),
@type = oldSchema.type,
vendorExtensions = new Dictionary<string, object>( oldSchema.vendorExtensions )
;
// Find model properties with the custom attribute.
foreach ( PropertyInfo property in properties )
ApiRequiredAttribute attribute = property.GetCustomAttribute<ApiRequiredAttribute>();
if ( attribute != null )
I then add the filter to my EnableSwagger call.
GlobalConfiguration.Configuration
.EnableSwagger("docs/swagger/", c =>
// Other initialization code...
c.OperationFilter<ApplyRequiredAttributeFilter>();
);
The attributes are used like so:
[ApiRequired( RequiredInPost = true, RequiredInPut = true)]
public bool? Active
get;
set;
[ApiRequired( RequiredInPost = true )]
public string UserName
get;
set;
Finally, on the docs, the required flags look like this. The POST method parameters are on the left while the PUT method paramaters are on the right:
add a comment |
I've managed to find a solution!
I created an IOperationFilter
that creates new schemas for POST and PUT methods, based on properties with my custom ApiRequired
attribute (see original question).
internal class ApplyRequiredAttributeFilter : IOperationFilter
public void Apply( Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription )
HttpParameterBinding[] parameterBindings = apiDescription.ActionDescriptor.ActionBinding.ParameterBindings;
foreach ( HttpParameterBinding binding in parameterBindings )
PropertyInfo[] properties = binding.Descriptor.ParameterType.GetProperties();
// If the type is not an object and has no properties, ignore it.
if ( properties.Length == 0 )
continue;
Parameter modelParamater = operation.parameters.Last();
if ( modelParamater == null )
continue;
string schemaPath = modelParamater.schema?.@ref;
string schemaName = schemaPath?.Split( '/' ).Last();
if ( schemaName == null )
continue;
Schema oldSchema = schemaRegistry.Definitions[ schemaName ];
// Copy the existing schema.
Schema newSchema = new Schema
description = oldSchema.description,
properties = new Dictionary<string, Schema>( oldSchema.properties ),
required = oldSchema.required != null ? new List<string>( oldSchema.required ) : new List<string>(),
@type = oldSchema.type,
vendorExtensions = new Dictionary<string, object>( oldSchema.vendorExtensions )
;
// Find model properties with the custom attribute.
foreach ( PropertyInfo property in properties )
ApiRequiredAttribute attribute = property.GetCustomAttribute<ApiRequiredAttribute>();
if ( attribute != null )
I then add the filter to my EnableSwagger call.
GlobalConfiguration.Configuration
.EnableSwagger("docs/swagger/", c =>
// Other initialization code...
c.OperationFilter<ApplyRequiredAttributeFilter>();
);
The attributes are used like so:
[ApiRequired( RequiredInPost = true, RequiredInPut = true)]
public bool? Active
get;
set;
[ApiRequired( RequiredInPost = true )]
public string UserName
get;
set;
Finally, on the docs, the required flags look like this. The POST method parameters are on the left while the PUT method paramaters are on the right:
add a comment |
I've managed to find a solution!
I created an IOperationFilter
that creates new schemas for POST and PUT methods, based on properties with my custom ApiRequired
attribute (see original question).
internal class ApplyRequiredAttributeFilter : IOperationFilter
public void Apply( Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription )
HttpParameterBinding[] parameterBindings = apiDescription.ActionDescriptor.ActionBinding.ParameterBindings;
foreach ( HttpParameterBinding binding in parameterBindings )
PropertyInfo[] properties = binding.Descriptor.ParameterType.GetProperties();
// If the type is not an object and has no properties, ignore it.
if ( properties.Length == 0 )
continue;
Parameter modelParamater = operation.parameters.Last();
if ( modelParamater == null )
continue;
string schemaPath = modelParamater.schema?.@ref;
string schemaName = schemaPath?.Split( '/' ).Last();
if ( schemaName == null )
continue;
Schema oldSchema = schemaRegistry.Definitions[ schemaName ];
// Copy the existing schema.
Schema newSchema = new Schema
description = oldSchema.description,
properties = new Dictionary<string, Schema>( oldSchema.properties ),
required = oldSchema.required != null ? new List<string>( oldSchema.required ) : new List<string>(),
@type = oldSchema.type,
vendorExtensions = new Dictionary<string, object>( oldSchema.vendorExtensions )
;
// Find model properties with the custom attribute.
foreach ( PropertyInfo property in properties )
ApiRequiredAttribute attribute = property.GetCustomAttribute<ApiRequiredAttribute>();
if ( attribute != null )
I then add the filter to my EnableSwagger call.
GlobalConfiguration.Configuration
.EnableSwagger("docs/swagger/", c =>
// Other initialization code...
c.OperationFilter<ApplyRequiredAttributeFilter>();
);
The attributes are used like so:
[ApiRequired( RequiredInPost = true, RequiredInPut = true)]
public bool? Active
get;
set;
[ApiRequired( RequiredInPost = true )]
public string UserName
get;
set;
Finally, on the docs, the required flags look like this. The POST method parameters are on the left while the PUT method paramaters are on the right:
I've managed to find a solution!
I created an IOperationFilter
that creates new schemas for POST and PUT methods, based on properties with my custom ApiRequired
attribute (see original question).
internal class ApplyRequiredAttributeFilter : IOperationFilter
public void Apply( Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription )
HttpParameterBinding[] parameterBindings = apiDescription.ActionDescriptor.ActionBinding.ParameterBindings;
foreach ( HttpParameterBinding binding in parameterBindings )
PropertyInfo[] properties = binding.Descriptor.ParameterType.GetProperties();
// If the type is not an object and has no properties, ignore it.
if ( properties.Length == 0 )
continue;
Parameter modelParamater = operation.parameters.Last();
if ( modelParamater == null )
continue;
string schemaPath = modelParamater.schema?.@ref;
string schemaName = schemaPath?.Split( '/' ).Last();
if ( schemaName == null )
continue;
Schema oldSchema = schemaRegistry.Definitions[ schemaName ];
// Copy the existing schema.
Schema newSchema = new Schema
description = oldSchema.description,
properties = new Dictionary<string, Schema>( oldSchema.properties ),
required = oldSchema.required != null ? new List<string>( oldSchema.required ) : new List<string>(),
@type = oldSchema.type,
vendorExtensions = new Dictionary<string, object>( oldSchema.vendorExtensions )
;
// Find model properties with the custom attribute.
foreach ( PropertyInfo property in properties )
ApiRequiredAttribute attribute = property.GetCustomAttribute<ApiRequiredAttribute>();
if ( attribute != null )
I then add the filter to my EnableSwagger call.
GlobalConfiguration.Configuration
.EnableSwagger("docs/swagger/", c =>
// Other initialization code...
c.OperationFilter<ApplyRequiredAttributeFilter>();
);
The attributes are used like so:
[ApiRequired( RequiredInPost = true, RequiredInPut = true)]
public bool? Active
get;
set;
[ApiRequired( RequiredInPost = true )]
public string UserName
get;
set;
Finally, on the docs, the required flags look like this. The POST method parameters are on the left while the PUT method paramaters are on the right:
edited Mar 29 at 13:45
answered Mar 29 at 9:01
Matt CleggMatt Clegg
933 silver badges13 bronze badges
933 silver badges13 bronze badges
add a comment |
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55379920%2fhow-to-vary-the-required-fields-for-post-and-put-in-swashbuckle%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Yes you can use IDocumentFilter for that, give it a try and update this post if you get stuck
– Helder Sepulveda
Mar 29 at 2:00