如何修复在Azure中托管ASP.NET Core 6 Web API时的Swagger错误

tv6aics1  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(133)

我在Azure上托管了我的ASP.NET Core 6 Web API项目,但在发布项目时显示错误。
无法在ConfigureServices方法中检测到AddSwaggerGen或ConfigureSwaggerGen的任何使用,正在跳过API更新
预热站点的调用失败,响应代码为:'InternalServerError'。
我在Swagger配置中做了一些修改,但仍然没有解决。

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Safari_Wave.Models;
using Safari_Wave.Repository;
using Safari_Wave.Repository.Interface;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace Safari_Wave
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.AllowAnyOrigin() // Update with your React app URL
                   .AllowAnyHeader()
                   .AllowAnyMethod();
                });
            });

            // Add session configuration
            builder.Services.AddDistributedMemoryCache();
            builder.Services.AddSession(options =>
            {
                options.Cookie.Name = "SafariWave";
                options.IdleTimeout = TimeSpan.FromSeconds(10);
                options.Cookie.IsEssential = true;
            });

            // Add Authentication
            builder.Services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
                .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = true,
                    //ValidIssuer = builder.Configuration["Jwt:Issuer"],
                    //ValidAudience = builder.Configuration["Jwt:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
                };
            });

            builder.Services.AddControllers().AddJsonOptions(x =>
                x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles).AddNewtonsoftJson(option =>
                {
                    option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                }); ;

            builder.Services.AddAutoMapper(typeof(Program));

            builder.Services.AddDbContext<SafariWaveContext>(options =>
            {
                options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
            });

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "Safari Wave API",
                    Version = "v1",
                });
            });
            
            builder.Services.AddSingleton<SMSService>(provider =>
            {
                var accountSid = builder.Configuration["Twilio:Sid"];
                var authToken = builder.Configuration["Twilio:Token"];
                var verifySid = builder.Configuration["Twilio:verifySid"];
                var logger = provider.GetRequiredService<ILogger<SMSService>>();

                return new SMSService(accountSid, authToken, logger, verifySid);
            });

            builder.Services.AddHttpContextAccessor();
            builder.Services.AddScoped<IPackageManagement, PackageManagement>();
            builder.Services.AddScoped<IUserManagement, UserManagement>();
            builder.Services.AddScoped<IBookingSevice, BookingService>();
            builder.Services.AddScoped<IEnquiryService, EnquiryService>();
            builder.Services.AddScoped<IReviewServices, ReviewService>();
            builder.Services.AddScoped<IOrderService, OrderService>();
            builder.Services.AddScoped<SaveImage>();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.RoutePrefix = String.Empty;
            });
           
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.ContentRootPath, "coverImage")),
                RequestPath = "/coverImage"
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(app.Environment.ContentRootPath, "Image")),
                RequestPath = "/Image"
            });

            app.UseHttpsRedirection();
            app.UseCors();
            app.UseSession();

            app.UseAuthentication();
            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}

浏览器中显示的错误是

我在useSwagger中进行了一些配置更改

owfi6suc

owfi6suc1#

最初我得到了下面的错误。

  • 已将Visual Studio更新为最新可用版本

  • 我在Swagger中做了一些修改,下面的代码对我很有效。
  • 我的Program.cs文件:*
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Safari Wave API",
        Version = "v1",
    });
});
----------
----------
var app = builder.Build();
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");

    if (app.Environment.IsDevelopment())
    {
        options.RoutePrefix = "swagger";
    }
    else
    {
        options.RoutePrefix = string.Empty;
    }
});
  • 本地应用:*

  • 部署应用:*

相关问题