You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Swashbuckle.Swagger手动添加MVC伪API端点至Swagger?

Absolutely! You can absolutely add "fake" endpoints to Swagger to expose these JSON responses, even if they don't exist as dedicated WebAPI actions in your MVC controller. Here's a straightforward way to do this using Swashbuckle.AspNetCore (the most common Swagger implementation for ASP.NET):

Step 1: Create a Custom Document Filter

Document filters let you modify the generated Swagger document directly. We’ll use one to inject our fake endpoints and link them to your actual JSON response model.

public class CustomJobEndpointsFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        // Define the pseudo-endpoints you want to expose
        var jobPaths = new[] { "/painter", "/plumber" };
        
        foreach (var path in jobPaths)
        {
            // Build the GET operation for the path
            var getOperation = new OpenApiOperation
            {
                Summary = $"Fetch JSON data for {path.TrimStart('/')}",
                Description = "Add the `?json=1` query parameter to trigger a JSON response instead of HTML",
                Parameters = new List<OpenApiParameter>
                {
                    new OpenApiParameter
                    {
                        Name = "json",
                        In = ParameterLocation.Query,
                        Required = true,
                        Schema = new OpenApiSchema { Type = "integer", Default = new OpenApiInteger(1) },
                        Description = "Set to 1 to return JSON-formatted job data"
                    }
                },
                Responses = new OpenApiResponses
                {
                    ["200"] = new OpenApiResponse
                    {
                        Description = "Successfully returned job data in JSON format",
                        Content = new Dictionary<string, OpenApiMediaType>
                        {
                            ["application/json"] = new OpenApiMediaType
                            {
                                // Replace YourJobModel with your actual response model class
                                Schema = context.SchemaGenerator.GenerateSchema(typeof(YourJobModel), context.SchemaRepository)
                            }
                        }
                    }
                }
            };

            // Add the operation to the Swagger document
            if (!swaggerDoc.Paths.ContainsKey(path))
            {
                swaggerDoc.Paths.Add(path, new OpenApiPathItem());
            }
            swaggerDoc.Paths[path].AddOperation(OperationType.Get, getOperation);
        }
    }
}

Step 2: Register the Filter in Your Swagger Configuration

Add the filter to your Swagger setup so it runs when the document is generated. For .NET 6+ projects, this goes in Program.cs:

builder.Services.AddSwaggerGen(c =>
{
    // Register your custom document filter
    c.DocumentFilter<CustomJobEndpointsFilter>();
    
    // Keep your existing Swagger configuration here
});

Bonus: Handle Different Models per Path

If /painter and /plumber return slightly different models, you can adjust the filter to map each path to its specific model type:

var pathToModelMap = new Dictionary<string, Type>
{
    ["/painter"] = typeof(PainterJobModel),
    ["/plumber"] = typeof(PlumberJobModel)
};

foreach (var entry in pathToModelMap)
{
    var path = entry.Key;
    var modelType = entry.Value;
    
    // Build the operation using modelType instead of a generic YourJobModel
    var getOperation = new OpenApiOperation
    {
        // ... (keep summary/description/parameters the same)
        Responses = new OpenApiResponses
        {
            ["200"] = new OpenApiResponse
            {
                Description = "Successfully returned job data in JSON format",
                Content = new Dictionary<string, OpenApiMediaType>
                {
                    ["application/json"] = new OpenApiMediaType
                    {
                        Schema = context.SchemaGenerator.GenerateSchema(modelType, context.SchemaRepository)
                    }
                }
            }
        }
    };
    
    // Add the operation to the Swagger document
    if (!swaggerDoc.Paths.ContainsKey(path))
    {
        swaggerDoc.Paths.Add(path, new OpenApiPathItem());
    }
    swaggerDoc.Paths[path].AddOperation(OperationType.Get, getOperation);
}

Why This Works

  • No changes needed to your existing MVC controllers or routing logic—this purely modifies the Swagger document to expose these pseudo-endpoints.
  • Designers can view the full response model structure directly in the Swagger UI, and even use the "Try it out" feature to test the endpoint (since the actual /painter?json=1 route already works, the test will return valid JSON).

内容的提问来源于stack exchange,提问作者MazeezaM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:27:53