Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

Create Common Function to return response codes in .Net Core 3.1 Web API

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In general I would strictly separate data access and return codes of the web API. So I'd first go with some kind of repository to query data:

public abstract class RepositoryBase
{
  protected void Validate(dynamic dynamicObjectData) { ... }
}

I would not use stored procedures, but operate on context with EF entities (all queries are typed), but I guess you have a good reason to use SPs, so you could go with:

public class CompanyRepository : RepositoryBase
{
  public void UpsertCompany(Company company)
  {
      var result = _context.Set<sp_Upsert_Company>().FromSqlInterpolated($"sp_Upsert_Company {master_Company.Name},{uID}").ToList().FirstOrDefault();
      Validate(result);
  }
}

Validate function shall throw exceptions if something is wrong:

if (dynamicObjectData.Code == -400)
        {
            throw new MyNotFoundException();
        }

So data layer queries data and throws if something bad happens.

Now you register a central exception handler on your ApplicationBuilder:

app.UseExceptionHandler(
   builder => builder.Run(async context =>
   {
      var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();
      if (exceptionFeature != null)
      {
         var exception = exceptionFeature.Error;
         // Handle all your app exceptions in one place and decide which code to return, create a custom error:
         ...
         context.Response.StatusCode = error.StatusCode; // Choose based on exception
         await context.Response.WriteAsync(JsonConvert.SerializeObject(error));
      })

So you encapsulate bad return codes with exceptions, catch them in one place, and decide what HTTP code to return.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...