in C# .net6 api controller, Im returning data with Ok IActionResult, below is my code, there i want to pass a string message along with return Ok(employee); Is it possible if so, please suggest how to do it?
[Route("{Id}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Employee))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetEmployeeDetails(int Id)
{
var listEmployees = new List<Employee>()
{
new Employee(){ Id = 1001, Name = "Anurag", Age = 28, City = "Mumbai", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1002, Name = "Pranaya", Age = 28, City = "Delhi", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1003, Name = "Priyanka", Age = 27, City = "BBSR", Gender = "Female", Department = "HR"},
};
var employee = listEmployees.FirstOrDefault(emp => emp.Id == Id);
if (employee != null)
{
**return Ok(employee);**
}
else
{
return NotFound();
}
}
CodePudding user response:
In order to return the message with the data as well, I would suggest creating a model class that allows returning multiple values.
For example, an ApiResponse
class that support generic type.
public class ApiResponse<T>
{
public string Message { get; set; }
public T Data { get; set; }
}
And your controller action to return the value of ApiResponse<Employee>
type for the status 200 scenario as below:
[Route("{Id}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ApiResponse<Employee>))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetEmployeeDetails(int Id)
{
var listEmployees = new List<Employee>()
{
new Employee(){ Id = 1001, Name = "Anurag", Age = 28, City = "Mumbai", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1002, Name = "Pranaya", Age = 28, City = "Delhi", Gender = "Male", Department = "IT" },
new Employee(){ Id = 1003, Name = "Priyanka", Age = 27, City = "BBSR", Gender = "Female", Department = "HR"},
};
var employee = listEmployees.FirstOrDefault(emp => emp.Id == Id);
if (employee != null)
{
return Ok(new ApiResponse<Employee>
{
Message = "Assign your message here",
Data = employee
});
}
else
{
return NotFound();
}
}
CodePudding user response:
Unfortunately don't think that is possible to do. The workaround could be that you add an extra field to the Employee object such as a string of description that gets returned as a whole.