Home > Software engineering >  Swagger not displaying routes/requests
Swagger not displaying routes/requests

Time:02-03

I have recently been attempting to add swagger to my project, ive followed all the guides but something seems to have gone wrong, ive used swagger for years but ive never had this issue before. It seems that its completely ignoring most of my routes and just using the PUT function, i cant explain it, but ive attached an image of my swagger and all the relevant code, i hope someone has experienced this befiore

Image of my swagger: https://prnt.sc/o7aIJEz0r7xc

Swaggerconfig:

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");
        });
    }
}

Httproute:

            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);

Controller: {

[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);
    }

CodePudding user response:

.net 6 swagger setup

                                      **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();

CodePudding user response:

After a few hours of pain i realized that i had forgotten the most important part

            config.MapHttpAttributeRoutes();

Thank you everyone for trying to help my broken mind <3.

  • Related