We are working on a Web API Project built using ASP.Net Core3.1 and we are wondering if the following is possible -
We are using Stored Procedures to handle INSERT / UPDATE queries and based on the validation, returning different status codes as below.
public async Task<IActionResult> PutCompany(Company company)
{
var data = _context.Set<sp_Upsert_Company>().FromSqlInterpolated($"sp_Upsert_Company {master_Company.Name},{uID}").ToList().FirstOrDefault();
if (data.Code == -400)
{
return NotFound(new NotFoundAPIResponse());
}
else if (data.Code == -300)
{
return Ok(new ErrorAPIResponse("Duplicate Data Found"));
}
else
return Ok(response);
}
We're returning different codes for different scenarios (-400, -300 etc.) and the codes are consistent across entire project. We're thinking to encapsulate the return code checking lines into a function in a separate common class like below -
public IActionResult Validate(dynamic dynamicObjectData)
{
if (dynamicObjectData.Code == -400)
{
return NotFound(new NotFoundAPIResponse());
}
else if (dynamicObjectData.Code == -300)
{
return Ok(new ErrorAPIResponse("Duplicate Data Found"));
}
return Ok(response);
}
Once the above is encapsulated in a different class, we would like to change the controller function as below -
public async Task<IActionResult> PutCompany(Company company)
{
var data = _context.Set<sp_Upsert_Company>().FromSqlInterpolated($"sp_Upsert_Company {master_Company.Name},{uID}").ToList().FirstOrDefault();
if ((!Validate(data) is OkResult))
{
return Validate(data);
}
else
{
//Do whatever we want to do
}
}
Please suggest. Thanks in advance.