Swagger未显示路线/请求

qni6mghb  于 2023-02-04  发布在  其他
关注(0)|答案(2)|浏览(148)

我最近一直在尝试添加swagger到我的项目,我遵循了所有的指南,但似乎出了问题,我使用swagger多年,但我从来没有这个问题之前。它似乎完全忽略了我的大部分路线,只是使用PUT函数,我不能解释它,但我附上了我的swagger和所有相关代码的图像,我希望有人有经验之前
我 Swagger 的形象:https://prnt.sc/o7aIJEz0r7xc
Swagger 配置:

public class SwaggerConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableSwagger(c => {
            c.SingleApiVersion("v1", "DefaultApi");
            c.ApiKey("Token")
.Description("Bearer token")
.Name("Authorization")
.In("header");
        }).EnableSwaggerUi(c =>
        {
            c.EnableApiKeySupport("Authorization", "header");
        });
    }
}

标题:

HttpConfiguration config = new HttpConfiguration();
        config.EnableCors();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        SwaggerConfig.Register(config);

        app.UseWebApi(config);

控制器:{

[Route("api/[controller]")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AuthController : ApiController
{
    public static DataContext DB = new DataContext();
    //public static string test = "This is my current test key";

    [HttpGet, Authorize(Roles = "Admin")]
    [Route("GetMe")]
    public IHttpActionResult GetMe()
    {
        var userName = User?.Identity?.Name;
        var identity = (ClaimsIdentity)User.Identity;
        IEnumerable<Claim> claims = identity.Claims;
        var role = identity.FindFirst(ClaimTypes.Role).Value;
        return Ok(new { userName, role, claims });
    }
    [HttpGet]
    [Route("CorsTest")]
    public IHttpActionResult CorsTest()
    {
        return Ok("xD");
    }

    //add role to user function

    //Users (gets all users)

    //

    [HttpPost]
    [Route("register")]
    public IHttpActionResult Register(UserRegister request)
    {
        if (request.Username.Equals("") || request.Password.Equals(""))
        {
            return BadRequest("Plase input username and password");
        }
        string query = "Select * from JWTUSER Where userName= '" + request.Username + "'";
        NpgsqlDataAdapter sda = new NpgsqlDataAdapter(query, DB.npgsqlConn);
        DataTable dataTable = new DataTable();
        sda.Fill(dataTable);
        if (dataTable.Rows.Count >= 1)
        {
            return BadRequest("This username is already being used");
        }
        User newUser = new User();
        CreatePasswordHash(request.Password, out byte[] passwordHash, out byte[] passwordSalt);
        newUser.Username = request.Username;
        newUser.Role = request.Role;
        newUser.PasswordHash = passwordHash;
        newUser.PasswordSalt = passwordSalt;
        newUser.Email = request.Email;
        newUser.PhoneNumber = request.PhoneNumber;
        DB.RegisterUser(newUser);
        return Ok(newUser);
    }
   [Authorize(Roles = "Admin")]
    [HttpPut]
    [Route("updateRole")]
    public IHttpActionResult UpdateRole(UpdateRole request)
    {
        //string userId = SubjectId
        //Replace body for register, instead of using username, extract username from database.
        User newUser = new User();
        if (request.Username.Equals(""))
        {
            return BadRequest("Plase input username");
        }
        string query = "Select * from JWTUSER Where userName= '" + request.Username + "'";
        NpgsqlDataAdapter sda = new NpgsqlDataAdapter(query, DB.npgsqlConn);
        DataTable dataTable = new DataTable();
        sda.Fill(dataTable);
        if (dataTable.Rows.Count > 1)
        {
            return BadRequest("Big error more then 1 user with this username");
        }
        if (dataTable.Rows.Count == 0)
        {
            return BadRequest("User not found");
        }
        foreach (var row in dataTable.AsEnumerable())
        {
            newUser.Username = row.Field<string>("userName");
            newUser.Role = row.Field<string>("role");
            newUser.PasswordHash = row.Field<byte[]>("passwordHash");
            newUser.PasswordSalt = row.Field<byte[]>("passwordSalt");
        }
        newUser.Role = request.Role;
        DB.UpdateRole(newUser);

        return Ok("Role update to " + newUser.Role);
    }
i7uaboj4

i7uaboj41#

.net 6 Swagger 设置

**Program.cs**

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSwaggerGen(opt =>
{
     opt.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
     {
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer",
        BearerFormat = "JWT",
        In = ParameterLocation.Header,
        Description =
        "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345.54321\""
     });
     opt.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
       {
          new OpenApiSecurityScheme
            { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } },
          new string[] { }
       }
    });
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
//Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
   app.UseSwagger();
   app.UseSwaggerUI();
}

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

app.MapControllers();

app.Run();
am46iovg

am46iovg2#

经过几个小时的痛苦,我意识到我忘记了最重要的部分

config.MapHttpAttributeRoutes();

谢谢大家努力帮助我破碎的心灵〈3。

相关问题