I just started learning aboout Api'sand started building a simple one. I built this EmployeeController:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
namespace ApiHandsOn1.Controllers
{
[Route("api/Employee")]
[ApiController]
public class EmployeeController : Controller
{
List<Employee> _employeeList = new List<Employee>()
{
new Employee()
{
Id=1,
Name= "abc def",
Salary=20000,
Permanent= true,
//Department= { Id = 1, Name = "Payroll"},
Skills ={new Skill{ Id= 1 , Value= "HTML"},new Skill{ Id= 2 , Value="CSS"},new Skill{ Id= 1 , Value= "JS"} },
DateOfBirth = new DateTime(01/03/2002)
},
new Employee()
{
Id=2,
Name= "ghi jkl",
Salary=25000,
Permanent= false,
//Department= { Id = 2, Name = "HR"},
Skills ={new Skill{ Id= 1 , Value= "HTML"},new Skill{ Id= 2 , Value="CSS"},new Skill{ Id= 1 , Value= "JS"} },
DateOfBirth = new DateTime(15/08/2005)
}
};
public EmployeeController()
{
}
private List<Employee> GetStandardEmployeeList()
{
return _employeeList;
}
// GET: EmployeeController
[HttpGet]
[Route("GetEmployees")]
[ProducesResponseType(StatusCodes.Status200OK)]
public List<Employee> GetStandard()
{
List<Employee> empList=GetStandardEmployeeList();
return empList;
}
}
}
I have built models for respective classes. But when I hit execute on Swagger, it throws an exception(at _employeeList):
System.NullReferenceException: 'Object reference not set to an instance of an object.'
What am I missing?
You need to initialize the Skills
property like this:
Skills = new List<Skill>(){new Skill{}, new Skill{}}
and as @smoksnes mentioned, you should put your value between literals in DateTime
Initialization
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.