如何在swagger中为.Net Core Web API设置基本路径属性 [英] How to set base path property in swagger for .Net Core Web API

查看:557
本文介绍了如何在swagger中为.Net Core Web API设置基本路径属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在ASP.Net Core(版本1.1.2)中构建了一个Web API,并且我使用Swashbuckle.AspNetCore生成了摇摇欲坠的定义.

i've built a Web API in ASP.Net Core (version 1.1.2) and i use the Swashbuckle.AspNetCore for generating the swagger definition.

是自动生成的摇摇定义的一部分.我想更改路径,使其不包含/api/ApiName ,但它会包含在 basePath 中,该名称现在为/

below is a part of the automatically generated swagger definition. i would like to change the paths so it does not include /api/ApiName but it would be included in the basePath which is now /

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/api/ApiName",
    "paths": {
        "/": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........

所以我想得到的是:

{
    "swagger": "2.0",
    "info": {
        "version": "v1",
        "title": "ApiName.V1"
    },
    "host": "ApiUrl",
    "basePath": "/",
    "paths": {
        "/api/ApiName": {
            "get": {
                "tags": [
                    "ApiName"
                ],
                .........

我们还有其他一些不是用.Net Core编写的API,它通过添加默认路由来解决同一问题.我尝试通过删除API控制器顶部的路由在.Net核心上执行相同的操作

We have some other APIs which are not written in .Net Core and there it fixed the same issue by adding default routes. I tried to do the same on .Net core by removing the route at the top of the API controller

[Route("api/[Controller]")]

并将其添加到Startup.cs.但是,这没有用.有谁知道如何解决这个问题?

and adding it to the Startup.cs. however this did not work. Does anyone have any idea on how to fix this?

推荐答案

最后我用它来解决它:

您可以设置PreSerializeFilters来添加BasePath和编辑路径.以为会有一种更优雅的方式,但这行得通.

you can set the PreSerializeFilters to add both the BasePath and edit the Paths. Thought there would be a more elegant way but this works.

var basepath = "/api/AppStatus";
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = basepath);


c.PreSerializeFilters.Add((swaggerDoc, httpReq) => {
    IDictionary<string, PathItem> paths = new Dictionary<string, PathItem>();
    foreach (var path in swaggerDoc.Paths)
    {
        paths.Add(path.Key.Replace(basepath, "/"), path.Value);
    }
    swaggerDoc.Paths = paths;
});

这篇关于如何在swagger中为.Net Core Web API设置基本路径属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆