After updating my project to .NET 6 and OData to 8.0.4, a new Metadata controller with these endpoints appeared:
I want to disable it somehow or remove it from my service.
Code for adding OData service:
ODataConfiguration.cs
public static void AddCustomOData(this IServiceCollection services)
{
services
.AddControllers(mvcOptions => mvcOptions.EnableEndpointRouting = false)
.AddOData(opt => opt.AddRouteComponents("", GetEdmModel()).Select().Expand());
}
Created custom attribute for controller [EnableOData]
:
public class EnableODataAttribute : EnableQueryAttribute
{
public override void ValidateQuery(HttpRequest request, ODataQueryOptions queryOptions)
{
try
{
queryOptions.Validate(new ODataValidationSettings());
}
catch (Exception e)
{
throw new ValidationException(e.Source, "Query parameter has not a valid value.");
}
}
}
Versions:
- .NET 6
- ASP.NET Core 6
- OData 8.0.4
CodePudding user response:
I recently faced the similar problem. I get the solution by
- removing odata service injection from startup file (because swagger automatically add metadata classes if I tried to inject odata from startup)
- downgrading OData from 8.0.4 to 8.0.0
- and implementing ODataQueryOptions inside controller instead of EnableQuery actionfilter
- used ODataBuilder/OdataModelBuilder within controller instead of startup. in my case it is ODataBuilder
CodePudding user response:
If you just need to hide Metadata controller and related schemas from the Swagger, try to use DocumentFilter:
public class SwaggerODataControllerDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
// remove controller
foreach (ApiDescription apiDescription in context.ApiDescriptions)
{
var actionDescriptor = (ControllerActionDescriptor)apiDescription.ActionDescriptor;
if (actionDescriptor.ControllerName == "Metadata")
{
swaggerDoc.Paths.Remove($"/{apiDescription.RelativePath}");
}
}
// remove schemas
foreach ((string key, _) in swaggerDoc.Components.Schemas)
{
if (key.Contains("Edm") || key.Contains("OData"))
{
swaggerDoc.Components.Schemas.Remove(key);
}
}
}
}
Add it to the services.AddSwaggerGen
:
cfg.DocumentFilter<SwaggerODataControllerDocumentFilter>();