Create Course Page
In this lesson, we're going to work on creating the course page
Create course page#
In the last lesson, we worked on the instructor page and we are giving an option to our instructors to create a new course. We haven't created an endpoint yet to create a course, so let's do that first inside CoursesController. We will authorize this function, and this time, we only want the instructor to create this course so we can write Roles to be equal to instructor. This will be a post request so let's write Http post. From this function, we will return a string so let's write public async Task ActionResult of type string. Let's call this method CreateCourse. We will pass data from body so let's mention FromBody and data will be of type course.
Inside this method, we will first set the instructor to be User.Identity.Name because this is an authorized request. After that, we can add the course to context dot course. Finally, we can write result which will be equal to context dot saveChangesAsync is greater than zero. If result is positive, we can return Course Created Successfully
. Otherwise, we can return BadRequest and pass new ApiResponse with status 400 and message Problem creating Course
.
API/Controllers/CoursesController.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using API.Dto;
using API.ErrorResponse;
using API.Helpers;
using AutoMapper;
using Entity;
using Entity.Interfaces;
using Entity.Specifications;
using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
public class CoursesController : BaseController
{
private readonly IMapper _mapper;
private readonly IGenericRepository<Course> _repository;
private readonly StoreContext _context;
public CoursesController(IGenericRepository<Course> repository, IMapper mapper, StoreContext context)
{
_context = context;
_repository = repository;
_mapper = mapper;
}
[HttpGet]
public async Task<ActionResult<Pagination<CourseDto>>> GetCourses([FromQuery] CourseParams courseParams)
{
var spec = new CoursesWithCategoriesSpecification(courseParams);
var countSpec = new CoursesFiltersCountSpecification(courseParams);
var total = await _repository.CountResultAsync(countSpec);
var courses = await _repository.ListWithSpec(spec);
if (courses == null) return NotFound(new ApiResponse(404));
var