Search code examples
c#swaggerasp.net-core-webapi

How to return all records based on type of course?


The Course model has few properties, one of them is

public string CourseType { get; set; } = null!;

For listing all courses my service (CourseService) contains

public List<Course> GetAllCourses()
{
    var Allcourses = _context.Courses.ToList();
    return Allcourses;
}

And the controller

//Get all Courses
[HttpGet("GetAllCourses")]
public IActionResult GetAllCourses()
{
    var allcourses = _courseservice.GetAllCourses();
    return Ok(allcourses);
}

How can I create a [HttpGet("GetElectives")] that only returns Courses where the CourseType is “Electives”?


Solution

  • First set the HttpMethodAttribute get to [HttpGet("GetElectives/{courseType}")] , this Attribute, makes your endpoint to able take parameter from url. Second you must develop your service to return by CourseType. Like this :

    public List<Course> GetCoursesByCourseType(string type)
    {
        var AllCourseType = _context.Courses.Where(a=>a.CourseType == type).ToList();
        return AllCourseType ;
    }