简体   繁体   中英

ASP.NET Core, .NET6 Adding a Controller to Swagger

I found it hard to integrate API to Swagger - there is only the default controller (WeatherForecast): 在此处输入图像描述

using Business.Repository.IRepository;
using Microsoft.AspNetCore.Mvc;

namespace HiddenVilla_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HotelRoomController : Controller
    {
        private readonly IHotelRoomRepository _hotelRoomRepository;

        public HotelRoomController(IHotelRoomRepository hotelRoomRepository)
        {
            _hotelRoomRepository = hotelRoomRepository;
        }
        /// <summary>
        /// Gets All hotel rooms
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        private async Task<IActionResult> GetHotelRooms()
        {
            var allRooms = await _hotelRoomRepository.GetAllHotelRoom();
            return Ok(allRooms);
        }
    }
}
using Business.Repository;
using Business.Repository.IRepository;
using DataAcess.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddScoped<IHotelRoomRepository, HotelRoomRepository>();
builder.Services.AddScoped<IHotelAmenityRepository, HotelAmenityRepository>();
builder.Services.AddScoped<IHotelImagesRepository, HotelImagesRepository>();
builder.Services.AddRouting(option => option.LowercaseUrls = true);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "HiddenVilla_Api", Version = "v1" });
});
builder.Services.AddMvc();
//builder.Services.AddMvcCore().AddApiExplorer();


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger(options => options.SerializeAsV2 = true);
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "HiddenVilla_Api v1"));
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

I think that maybe I'm missing something. The idea is for the controller to take the method from HotelRoolRepository. I have installed Swashbuckle.AspNetCore.Swagger, Swashbuckle.AspNetCore.SwaggerGen, Swashbuckle.AspNetCore.SwaggerUI

It's probably the fact that your action method is private . You should make it public .

Change this

private async Task<IActionResult> GetHotelRooms();

to

public async Task<IActionResult> GetHotelRooms();

Make method public instead of private. Add Attribute [HttpGet("GetHotelRooms")] this way.

 [HttpGet("GetHotelRooms")]
        public async Task<IActionResult> GetHotelRooms()
        {
            var allRooms = await _hotelRoomRepository.GetAllHotelRoom();
            return Ok(allRooms);
        }

It is because of routing problem.

1- Define HttpGet or HttpPost,...

if there are some action with same method(GET,POST,...), defining method route is required.

2- Define Route path

3- Define access modifier into public.

Private modifier does not throw any exception for swagger, private actions are not shown in swagger api list though.

        [HttpGet]
        [Route("GetPersonInfo")]
        public async Task<IActionResult> GetPersonInfo([FromBody] PersonInfoSearchItem searchItem)
        {
            return Ok(new
            {
                errorNumber = 2,
                message = "data is fetched successfully",
                Object= new Person()
            });
        }


    [HttpGet]
    [Route("SavePerson")]
    private async Task<IActionResult> SavePerson([FromBody] PersonInfoSearchItem searchItem)
    {
        return Ok(new
        {
            errorNumber = 0,
            message = "everything is Ok"
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM