【问题标题】:Unable to have access to swagger UI when launching my app启动我的应用程序时无法访问 swagger UI
【发布时间】:2022-07-21 09:19:15
【问题描述】:

我正在使用 ASP.NET Core 6,并使用 react 选项创建了我的应用程序(所以我的文件夹中有一个 ClientApp)。

当我运行应用程序时,我会看到我的反应 UI,而无法看到招摇的 UI。

通常当您选择从两个不同的文件夹构建frontend 和backend 时,如果您在Visual Studio 上运行后端,您将看到招摇的UI。

但是现在我只看到我的反应应用程序 UI。我正在尝试使用 https://localhost:44434/swagger 或 https://localhost:44434/swagger/index.html 访问招摇,但它只停留在我的反应应用 UI 页面上。

这是我尝试设置的视频:

https://www.youtube.com/watch?v=RvwvFmO-56E

有什么想法吗?非常感谢!

这是我的program.cs 代码:

    using BugTracker.Context;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

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

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{

    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    //app.UseHsts();
}
app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();


app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html"); ;

app.Run();

这是我的控制器代码:

using Microsoft.AspNetCore.Mvc;
using System;

namespace BugTracker.Controllers
{
    [ApiController]
    [Route("api/authentication")]
    public class AuthController : Controller
    {
        [HttpGet]
        public IActionResult Test()
        {
            return Ok("success");
        }
    }
}

【问题讨论】:

  • 我使用默认模板创建了一个新的 .net 6 react 项目。然后默认情况下不集成 Swagger ui。于是我安装了包Swashbuckle.AspNetCore,然后在Program.cs中添加了builder.Services.AddSwaggerGen();和app.UseSwagger(); app.UseSwaggerUI();,然后运行应用程序后,访问https://localhost:port/swagger/index.html,可以看到Swagger Ui
  • @TinyWang 好的,所以我注定要完蛋了,我拥有你列出的所有东西。当我访问第一个主页时,带有导航栏的默认应用程序的文本,但是当我去 swagger/index.html 时,只有导航栏停留并且文本消失并且它是一个空白页面。

标签: asp.net-core swagger asp.net-core-6.0


【解决方案1】:

如果您正在创建 WebAPI + React UI:

  1. 在Program.cs 文件中你应该添加builder.Services.AddControllers();

  2. 您的AuthController 类应该继承ControllerBase Controller.

  3. 在app.UseRouting(); 之后尝试使用app.UseEndpoints(endpoint =&gt; endpoint.MapControllers());

【讨论】:

  • 感谢您的回复,我仍然得到相同的行为。我真的不明白哈哈。
  • 不幸的是,您的代码中有多个冲突的行。我建议你应该从网上获得一个教程。如果您想学习如何构建 .net core apis 等,Les Jackson 很好。
【解决方案2】:

我遇到了完全相同的问题。没有任何效果(带有 NET 6 的 Angular SPA)。对于它的见鬼,我注释掉了说明说要使用的 2 行,它开始工作了!

app.UseSwaggerUI(options =>
{
// options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
// options.RoutePrefix = String.Empty;
});

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2020-02-25
    • 2015-05-22
    • 2018-06-08
    • 2021-06-03
    • 1970-01-01
    • 2022-07-29
    • 2018-05-29
    • 1970-01-01
    相关资源
    最近更新 更多