我正在尝试在 v4 Azure 函数中启用 swagger。 尽我所能地遵循示例。 我在本地运行时看到日志窗口中显示了 swagger 端点。
例如,
localhost:8190/api/swagger/ui
但是,当我导航到 swagger UI 端点时,我看到生成的 HTTP 500 和空白屏幕。
在
program.cs
using Microsoft.Extensions.Hosting;
using Microsoft.Azure.Functions.Worker.Extensions.OpenApi.Extensions;
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureOpenApi() // Enable OpenAPI
.Build();
host.Run();
函数类
using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
namespace MyFunctionApp
{
public static class MyFunction
{
[Function("MyFunction")]
[OpenApiOperation(operationId: "Run", tags: new[] { "name" })]
[OpenApiParameter(name: "name", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **Name** parameter")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(string), Description = "The OK response")]
public static HttpResponseData Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req)
{
var query = System.Web.HttpUtility.ParseQueryString(req.Url.Query);
string name = query["name"];
var response = req.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("Content-Type", "application/json");
var responseBody = JsonConvert.SerializeObject(new { message = $"Hello, {name}!" });
response.WriteString(responseBody);
return response;
}
}
}
[更新]
天啊@#$#$@#$,我想我应该启动一个新的功能应用程序并保持最低限度。 瞧,它成功了。 然后我比较了我所拥有的。 发现我的程序中出现了这一行。cs
.ConfigureWebHostDefaults()
把它拿出来,我的 swagger ui 就出现了。 那明显是踩到了什么东西。
我现在要去踢砖墙了
我确实同意并面临类似的问题,然后将其更改为
ConfigureFunctionsWebApplication
,然后它对我有用。
程序.cs:
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var rith = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureServices(test =>
{
test.AddApplicationInsightsTelemetryWorkerService();
test.ConfigureFunctionsApplicationInsights();
})
.Build();
rith.Run();
输出: