0
public class Books
{
   public int Id{get;set;}
   public string Name{get;set;}
}
  public class BookController : ODataController
    {
        private readonly IBookRepository _bookRepository;
        private readonly IMapper _mapper;

        public BookController(IBookRepository bookRepository, IMapper mapper)
        {
            _bookRepository = bookRepository;
            _mapper = mapper;
        }

        [EnableQuery]
        [HttpGet]
        public ActionResult Get()  
        {
            try
            {
                IQueryable<BookDto> res = _bookRepository.Books().ProjectTo<BookDto>(_mapper.ConfigurationProvider);

                if (res.Count() == 0)
                    return NotFound();

                return Ok(res);

            }
            catch(Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "Unable to get Book");
            }
        }

        [HttpGet("{Id}")]
        public async Task<ActionResult<Book>> GetBookById(string Id)
        {
            var book = await  _bookRepository.GetBookById(Id);

            if (book == null)
                return NotFound();

            return book;
        }
     
        [HttpPost]
        public async Task<ActionResult<Book>> Post([fr]CreateBookDto  createBookDto)
        {
            try
            {
                if (createBookDto == null)
                    return BadRequest();

                Book book = _mapper.Map<Book>(createBookDto);

                var result = await _bookRepository.Book(book);

                return CreatedAtAction(nameof(GetBookById), new { id = book.UserId }, result);

            }
            catch (Exception)
            {
               return StatusCode(StatusCodes.Status500InternalServerError,"Failed to save Book information");
            }

        }
    }
 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            var connectionStr = Configuration.GetConnectionString("ConnectionString");
            services.AddControllers();
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddControllers().AddOData(opt => opt.AddRouteComponents("api",GetEdModel()).Select().Filter().Count().Expand());
            services.AddDbContext<AppDbContext>(options => options.UseMySql(connectionStr,ServerVersion.AutoDetect(connectionStr)));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Book_api", Version = "v1" });
            });

            services.AddScoped<IBookRepository, BookRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Book_api v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

        }

        private IEdmModel GetEdModel()
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<User>("User");
            builder.EntitySet<BookDto>("Book");
    
            return builder.GetEdmModel();
        }
    }

Hi Guys. I'm trying to implement OData on my ASP.Net Core 5 API. I can retrieve books using the Get. But I am struggling to do a POST. When I try to use the POST on Postman, the CreateBookDto properties all return null. I tried to add [FromBody] that does not work also. The only time this seems to work is when I decorate the controller with [ApiController] but that in turn affects my GET. I'm not sure what to do anymore.

Java_Dude
  • 97
  • 9

0 Answers0