Rest-API-with-ASP.NET-Core-2

Building a Rest API with ASP.NET Core 2 & Entity Framework Core 2


Project maintained by kdakan Hosted on GitHub Pages — Theme by mattgraham

https://kdakan.github.io/Rest-API-with-ASP.NET-Core-2/

BUILDING A REST API WITH ASP.NET CORE 2 & EF CORE 2

Table of contents

1. ASP.NET Core

2. MVC:

3. HTTP status code levels:

4. HTTP actions and proper responses:

The correct HTTP status codes and payloads for a REST API are listed as follows:

5. Global error handling:

6. Logging with NLog:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler(appBuilder =>
    {
        appBuilder.Run(async context =>
        {
            var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>();
            if (exceptionHandlerFeature != null)
            {
                var logger = loggerFactory.CreateLogger("Global exception logger");
                logger.LogError(500,
                    exceptionHandlerFeature.Error,
                    exceptionHandlerFeature.Error.Message);
            }

            context.Response.StatusCode = 500;
            await context.Response.WriteAsync("An unexpected fault happened. Try again later.");

        });                      
    });
}

7. Content negotiation:

8. IOC and dependency injection:

9. Configuration files and environment variables:

10. Entity Framework Core 2:

11. DTO’s and AutoMapper:

12. Async actions:

var task1 = GetBookAsync(1);
var task2 = GetBookAsync(2);
var task3 = GetBookAsync(3);

await Task.WhenAll(task1, task2, task3);

Console.WriteLine(String.Join(", ", task1.Result, task2.Result, task3.Result));

13. Paging, filtering, and sorting resources:

14. HTTP cache:

Static web pages, images, or static data like definitions, cities, countries, currencies, etc. can be served from an HTTP cache to reduce network traffic or reduce server load on the API.

There are three types of HTTP cache:

15. HTTP cache expiration and validation:

HTTP cache integrates both expiration and validation to reduce network traffic between clients and the API

HTTP cache expiration:

HTTP cache validation:

16. Example HTTP cache flow:

17. Using HTTP cache and concurrency control:

18. Consuming an API with HttpClient:

private async Task<Book> GetBookAsync(
HttpClient httpClient, string id, CancellationToken cancellationToken)
{
    //throw new Exception("Cannot get book...");

    var response = await httpClient
               .GetAsync(id, cancellationToken);

    if (response.IsSuccessStatusCode)
    {
        var book = JsonConvert.DeserializeObject<Book>(
            await response.Content.ReadAsStringAsync());
        return book;
    }

    _cancellationTokenSource.Cancel();

    return null;
}