Swagger UI displaying the asp.net webapi parameter

2019-07-18 18:59发布

I have configured Swagger for my asp.net webapi which is similar to one shown below

[HttpGet]
[Route("search")]
public async Task<HttpResponseMessage> Get([FromUri]SearchCriteria searchCriteria)

When i see the swagger documentation for the webapi , the parameter is displaying as

searchCriteria.sortField searchCriteria.sortDirection and so on... being the sortField, sortDirection are properties of SearchCriteria

enter image description here

How to get the parameter names without the object.propertyname format?

Can anyone help how to fix this? Thanks

3条回答
Root(大扎)
2楼-- · 2019-07-18 19:34

When you pass parameter Name = "" to the FormUri attribute Swashbuckle generates parameter names in unqualified form e.g. sortField instead of searchCriteria.sortField.

public async Task<HttpResponseMessage> Get([FromUri(Name = "")]SearchCriteria searchCriteria)
查看更多
虎瘦雄心在
3楼-- · 2019-07-18 19:43

I assume you are using Swashbuckle.

Look at DocumentFilters and OperationFilters. You can extend Swashbuckle to intervene at the document or operation level to modify the output.

Read through the Swashbuckle documentation, it is fairly straight forward to implement either of these two interfaces.

查看更多
老娘就宠你
4楼-- · 2019-07-18 19:55

Here's an OperationFilter I once used to remove the class name from query parameters.

public class ParameterFilter : IOperationFilter
{
    private const string Pattern = @"^ # Match start of string
                .*? # Lazily match any character, trying to stop when the next condition becomes true
                \.  # Match the dot";
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.parameters == null)
        {
            return;
        }

        foreach (var parameter in operation.parameters
            .Where(x => x.@in == "query" && x.name.Contains(".")))
        {
            parameter.name = Regex.Replace(
                parameter.name,
                Pattern, 
                string.Empty, 
                RegexOptions.IgnorePatternWhitespace);
        }
    }
}

Add it to you SwaggerConfig like this:

GlobalConfiguration.Configuration
    .EnableSwagger(c =>
        {
            // other settings omitted
            c.OperationFilter<ParameterFilter>();    
        }); 

BTW: The regex is inspired by https://stackoverflow.com/a/7794128/502395

查看更多
登录 后发表回答