【问题标题】:Need help setting my default API Route on SwashBuckle (AzureFunctions)需要帮助在 SwashBuckle (AzureFunctions) 上设置我的默认 API 路由
【发布时间】:2020-06-02 18:19:52
【问题描述】:

所以 TL;DR 我一直在学习如何将 shwashbuckle 合并到 Azure Functions 中,到目前为止它运行良好,但我无法更改我的默认路由前缀。

我能够更改许多其他属性,例如标题、服务器等,但我确实需要默认 api 以 /path 而不是 /api/path 的形式出现,如果这有意义的话。

我将在下面发布我的代码,希望你们中的一些人能够帮助我。

功能:

namespace SwashBuckleExample.Functions.Functions
{
    public class GetClubByClubNameHttp
    {
        private ISwashBuckleExampleProcess _process;
        private ILogger<GetClubByClubNameHttp> _logger;

        public GetClubByClubNameHttp(ISwashBuckleExampleProcess process, ILogger<GetClubByClubNameHttp> logger)
        {
            _process = process;
            _logger = logger;
        }

        /// <summary>
        /// Function that runs GetClubByNameProcess
        /// </summary>
        /// <param name="req">HttpRequest</param>
        /// <returns>SwashBuckleExampleSuccessResponse Item</returns>
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(SwashBuckleExampleSuccessResponse))]
        [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(SwashBuckleExampleBaseResponse))]
        [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(SwashBuckleExampleBaseResponse))]
        [FunctionName("GetClubByClubNameHttp")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] 
            [RequestBodyType(typeof(SwashBuckleExampleClubNameRequest), "Contains Club Name used for searching purposes")]HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function UpdateClientHttp");

            //Read Query parameters

            //Read RequestBody
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            //Decouple Requests

            SwashBuckleExampleClubNameRequest request = JsonConvert.DeserializeObject<SwashBuckleExampleClubNameRequest>(requestBody);

            //Make all pipeline Request
            var responseObject = _process.GetClubByNameProcess(request);
            return !responseObject.HasErrors ? (ObjectResult)new OkObjectResult(responseObject) : (ObjectResult)new BadRequestObjectResult(responseObject);
        }
    }
}

SwashBuckleStartup:

using System.Reflection;
using AzureFunctions.Extensions.Swashbuckle;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using SwashBuckleExample.Functions;
using SwashBuckleExample.Functions.SwaggerFunctions.SwaggerDocumentFilter;

[assembly: WebJobsStartup(typeof(SwashBuckleStartup))]
namespace SwashBuckleExample.Functions
{
    internal class SwashBuckleStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            //Register the extension
            builder.AddSwashBuckle(Assembly.GetExecutingAssembly(), c => 
            {
                c.ConfigureSwaggerGen = (d => d.DocumentFilter<SwashBuckleExampleDocumentFilter>());
            });            
        }
    }
}

文档过滤器:

namespace SwashBuckleExample.Functions.SwaggerFunctions.SwaggerDocumentFilter
{
    public class SwashBuckleExampleDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Info.Title = "SwashBuckleExample";
            swaggerDoc.Info.Version = "v1";
            swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "LinkToServer" } };
        }
    }
}

感谢您的帮助。

ps:

我需要删除这个总是出现但我不知道为什么的参数。有什么办法吗? Parameters

【问题讨论】:

    标签: c# .net-core swagger azure-functions swashbuckle


    【解决方案1】:

    1.如何更改 Azure 函数默认路由前缀。

    如果我们想改变Azure函数默认路由前缀,我们可以通过设置host.json中指定的routePrefix来实现。更多详情请参考herehere

    例如

    在您的 host.json 文件中添加以下设置。

    {
      "version": "2.0",
      "extensions": {
    
        "http": {
          "routePrefix" : ""
        }
      },
      ....
    }
    

    2.为什么你的 swagger 文件有查询参数code

    出现这种情况的原因是您将 Azure 函数 HTTP 触发器身份验证级别设置为 FunctionAdmin,代码为 HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]。之后,我们需要在调用函数时提供函数键或主机键以包含在名为code 的查询字符串变量中。它的 URL 应该是https://&lt;APP_NAME&gt;.azurewebsites.net/api/&lt;FUNCTION_NAME&gt;?code=&lt;API_KEY&gt;。更多详情请参考document

    例如

    我的代码

    [ProducesResponseType(typeof(TestModel[]), (int)HttpStatusCode.OK)]
            [FunctionName("TestGets")]
            public async Task<IActionResult> Gets([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "test")]
                HttpRequest request)
            {
                return new OkObjectResult(new[] { new TestModel(), new TestModel() });
            }
    
            [ProducesResponseType(typeof(TestModel), (int)HttpStatusCode.Created)]
            [FunctionName("TestAdd")]
            public Task<IActionResult> Add([HttpTrigger(AuthorizationLevel.Function, "post", Route = "test")]
                TestModel testModel)
            {
                return Task.FromResult<IActionResult>(new CreatedResult("", testModel));
            }
    

    所以如果要删除参数,请将代码更新为[HttpTrigger(AuthorizationLevel.Anonymous,...)

    例如 我的代码

    ProducesResponseType(typeof(TestModel), (int)HttpStatusCode.Created)]
            [FunctionName("TestAdd")]
            public Task<IActionResult> Add([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "test")]
                TestModel testModel)
            {
                return Task.FromResult<IActionResult>(new CreatedResult("", testModel));
            }
    

    【讨论】:

    • 没有AuthorizationLevel.Anonymous就没有办法去掉参数吗?我们通常将我们的函数上传到一个 FunctionApp 并通过 Azure Api Management 调用它,保留该代码是一个很好的安全措施,我只是不希望它大摇大摆地展示。
    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多