├── .github ├── get.jpg ├── post.jpg ├── put.jpg ├── delete.jpg ├── patch.jpg ├── getSingle.jpg ├── versions.jpg └── workflows │ └── dotnetcore.yml ├── docker_compse.yml ├── SampleWebApiAspNetCore ├── appsettings.Development.json ├── appsettings.json ├── Services │ ├── ISeedDataService.cs │ ├── ILinkService.cs │ ├── SeedDataService.cs │ └── LinkService.cs ├── Dtos │ ├── FoodUpdateDto.cs │ ├── FoodDto.cs │ └── FoodCreateDto.cs ├── Entities │ └── FoodEntity.cs ├── Models │ ├── LinkDto.cs │ └── QueryParameters.cs ├── Controllers │ ├── v2 │ │ └── FoodsController.cs │ └── v1 │ │ └── FoodsController.cs ├── Repositories │ ├── FoodDbContext.cs │ ├── IFoodRepository.cs │ └── FoodSqlRepository.cs ├── Helpers │ ├── DynamicExtensions.cs │ ├── SeedDataExtension.cs │ ├── CorsExtension.cs │ ├── ExceptionExtension.cs │ ├── QueryParametersExtensions.cs │ └── VersioningExtension.cs ├── Properties │ └── launchSettings.json ├── SampleWebApiAspNetCore.csproj ├── ConfigureSwaggerOptions.cs └── Program.cs ├── dockerfile ├── SampleWebApiAspNetCore.sln ├── Readme.md ├── .gitattributes └── .gitignore /.github/get.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/HEAD/.github/get.jpg -------------------------------------------------------------------------------- /.github/post.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/HEAD/.github/post.jpg -------------------------------------------------------------------------------- /.github/put.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/HEAD/.github/put.jpg -------------------------------------------------------------------------------- /.github/delete.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/HEAD/.github/delete.jpg -------------------------------------------------------------------------------- /.github/patch.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/HEAD/.github/patch.jpg -------------------------------------------------------------------------------- /.github/getSingle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/HEAD/.github/getSingle.jpg -------------------------------------------------------------------------------- /.github/versions.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FabianGosebrink/ASPNETCore-WebAPI-Sample/HEAD/.github/versions.jpg -------------------------------------------------------------------------------- /docker_compse.yml: -------------------------------------------------------------------------------- 1 | docker composefile 2 | 3 | version: '3.8' 4 | services: 5 | webapi: 6 | build: . 7 | ports: 8 | - "5000:5000" 9 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /dockerfile: -------------------------------------------------------------------------------- 1 | 2 | FROM mcr.microsoft.com/dotnet/sdk:6.0 3 | WORKDIR /app 4 | COPY . . 5 | RUN dotnet restore && dotnet publish -c Release -o out 6 | WORKDIR /app/out 7 | EXPOSE 5000 8 | ENTRYPOINT ["dotnet", "ASPNETCore-WebAPI-Sample.dll"] 9 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Services/ISeedDataService.cs: -------------------------------------------------------------------------------- 1 | using SampleWebApiAspNetCore.Repositories; 2 | 3 | namespace SampleWebApiAspNetCore.Services 4 | { 5 | public interface ISeedDataService 6 | { 7 | void Initialize(FoodDbContext context); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Dtos/FoodUpdateDto.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace SampleWebApiAspNetCore.Dtos 3 | { 4 | public class FoodUpdateDto 5 | { 6 | public string? Name { get; set; } 7 | public int Calories { get; set; } 8 | public string? Type { get; set; } 9 | public DateTime Created { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Dtos/FoodDto.cs: -------------------------------------------------------------------------------- 1 | namespace SampleWebApiAspNetCore.Dtos 2 | { 3 | public class FoodDto 4 | { 5 | public int Id { get; set; } 6 | public string? Name { get; set; } 7 | public string? Type { get; set; } 8 | public int Calories { get; set; } 9 | public DateTime Created { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Entities/FoodEntity.cs: -------------------------------------------------------------------------------- 1 | namespace SampleWebApiAspNetCore.Entities 2 | { 3 | public class FoodEntity 4 | { 5 | public int Id { get; set; } 6 | public string? Name { get; set; } 7 | public string? Type { get; set; } 8 | public int Calories { get; set; } 9 | public DateTime Created { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /.github/workflows/dotnetcore.yml: -------------------------------------------------------------------------------- 1 | name: .NET Core 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v3 12 | - name: Setup .NET Core 13 | uses: actions/setup-dotnet@v2 14 | with: 15 | dotnet-version: '7.0.x' 16 | - name: Build with dotnet 17 | run: dotnet build --configuration Release 18 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Dtos/FoodCreateDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace SampleWebApiAspNetCore.Dtos 4 | { 5 | public class FoodCreateDto 6 | { 7 | [Required] 8 | public string? Name { get; set; } 9 | public string? Type { get; set; } 10 | public int Calories { get; set; } 11 | public DateTime Created { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Models/LinkDto.cs: -------------------------------------------------------------------------------- 1 | namespace SampleWebApiAspNetCore.Models 2 | { 3 | public class LinkDto 4 | { 5 | public string Href { get; set; } 6 | public string Rel { get; set; } 7 | public string Method { get; set; } 8 | 9 | public LinkDto(string href, string rel, string method) 10 | { 11 | Href = href; 12 | Rel = rel; 13 | Method = method; 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Services/ILinkService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using SampleWebApiAspNetCore.Models; 3 | 4 | namespace SampleWebApiAspNetCore.Services 5 | { 6 | public interface ILinkService 7 | { 8 | object ExpandSingleFoodItem(object resource, int identifier, ApiVersion version); 9 | 10 | List CreateLinksForCollection(QueryParameters queryParameters, int totalCount, ApiVersion version); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Controllers/v2/FoodsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace SampleWebApiAspNetCore.Controllers.v2 4 | { 5 | [ApiController] 6 | [ApiVersion("2.0")] 7 | [Route("api/v{version:apiVersion}/[controller]")] 8 | public class FoodsController : ControllerBase 9 | { 10 | [HttpGet] 11 | public ActionResult Get() 12 | { 13 | return Ok("2.0"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Repositories/FoodDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using SampleWebApiAspNetCore.Entities; 3 | 4 | namespace SampleWebApiAspNetCore.Repositories 5 | { 6 | public class FoodDbContext : DbContext 7 | { 8 | public FoodDbContext(DbContextOptions options) 9 | : base(options) 10 | { 11 | } 12 | 13 | public DbSet FoodItems { get; set; } = null!; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Repositories/IFoodRepository.cs: -------------------------------------------------------------------------------- 1 | using SampleWebApiAspNetCore.Entities; 2 | using SampleWebApiAspNetCore.Models; 3 | 4 | namespace SampleWebApiAspNetCore.Repositories 5 | { 6 | public interface IFoodRepository 7 | { 8 | FoodEntity GetSingle(int id); 9 | void Add(FoodEntity item); 10 | void Delete(int id); 11 | FoodEntity Update(int id, FoodEntity item); 12 | IQueryable GetAll(QueryParameters queryParameters); 13 | ICollection GetRandomMeal(); 14 | int Count(); 15 | bool Save(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Models/QueryParameters.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace SampleWebApiAspNetCore.Models 3 | { 4 | public class QueryParameters 5 | { 6 | private const int maxPageCount = 50; 7 | public int Page { get; set; } = 1; 8 | 9 | private int _pageCount = maxPageCount; 10 | public int PageCount 11 | { 12 | get { return _pageCount; } 13 | set { _pageCount = (value > maxPageCount) ? maxPageCount : value; } 14 | } 15 | 16 | public string? Query { get; set; } = ""; 17 | 18 | public string OrderBy { get; set; } = "Name"; 19 | } 20 | } -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Helpers/DynamicExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.ComponentModel; 3 | using System.Dynamic; 4 | 5 | namespace SampleWebApiAspNetCore.Models 6 | { 7 | public static class DynamicExtensions 8 | { 9 | public static dynamic ToDynamic(this object value) 10 | { 11 | IDictionary expando = new ExpandoObject(); 12 | 13 | foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType())) 14 | { 15 | expando.Add(property.Name, property.GetValue(value)); 16 | } 17 | 18 | return expando as ExpandoObject; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Helpers/SeedDataExtension.cs: -------------------------------------------------------------------------------- 1 | using SampleWebApiAspNetCore.Repositories; 2 | using SampleWebApiAspNetCore.Services; 3 | 4 | namespace SampleWebApiAspNetCore.Helpers 5 | { 6 | public static class SeedDataExtension 7 | { 8 | public static void SeedData(this WebApplication app) 9 | { 10 | using (var scope = app.Services.CreateScope()) 11 | { 12 | var dbContext = scope.ServiceProvider.GetRequiredService(); 13 | var seedDataService = scope.ServiceProvider.GetRequiredService(); 14 | 15 | seedDataService.Initialize(dbContext); 16 | } 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Helpers/CorsExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace SampleWebApiAspNetCore.Helpers 4 | { 5 | public static class CorsExtension 6 | { 7 | public static void AddCustomCors(this IServiceCollection services, string policyName) 8 | { 9 | services.AddCors(options => 10 | { 11 | options.AddPolicy(policyName, 12 | builder => 13 | { 14 | builder 15 | .AllowAnyOrigin() 16 | .AllowAnyHeader() 17 | .AllowAnyMethod(); 18 | }); 19 | }); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Services/SeedDataService.cs: -------------------------------------------------------------------------------- 1 | using SampleWebApiAspNetCore.Entities; 2 | using SampleWebApiAspNetCore.Repositories; 3 | 4 | namespace SampleWebApiAspNetCore.Services 5 | { 6 | public class SeedDataService : ISeedDataService 7 | { 8 | public void Initialize(FoodDbContext context) 9 | { 10 | context.FoodItems.Add(new FoodEntity() { Calories = 1000, Type = "Starter", Name = "Lasagne", Created = DateTime.Now }); 11 | context.FoodItems.Add(new FoodEntity() { Calories = 1100, Type = "Main", Name = "Hamburger", Created = DateTime.Now }); 12 | context.FoodItems.Add(new FoodEntity() { Calories = 1200, Type = "Dessert", Name = "Spaghetti", Created = DateTime.Now }); 13 | context.FoodItems.Add(new FoodEntity() { Calories = 1300, Type = "Starter", Name = "Pizza", Created = DateTime.Now }); 14 | 15 | context.SaveChanges(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:27813", 8 | "sslPort": 44341 9 | } 10 | }, 11 | "profiles": { 12 | "SampleWebApiAspNetCore": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7124;http://localhost:5124", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/SampleWebApiAspNetCore.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Helpers/ExceptionExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Diagnostics; 2 | 3 | namespace SampleWebApiAspNetCore.Helpers 4 | { 5 | public static class ExceptionExtension 6 | { 7 | public static void AddProductionExceptionHandling(this IApplicationBuilder app, ILoggerFactory loggerFactory) 8 | { 9 | app.UseExceptionHandler(errorApp => 10 | { 11 | errorApp.Run(async context => 12 | { 13 | context.Response.StatusCode = 500; 14 | context.Response.ContentType = "text/plain"; 15 | var errorFeature = context.Features.Get(); 16 | if (errorFeature != null) 17 | { 18 | var logger = loggerFactory.CreateLogger("Global exception logger"); 19 | logger.LogError(500, errorFeature.Error, errorFeature.Error.Message); 20 | } 21 | 22 | await context.Response.WriteAsync("There was an error"); 23 | }); 24 | }); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32616.157 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleWebApiAspNetCore", "SampleWebApiAspNetCore\SampleWebApiAspNetCore.csproj", "{36DF3175-0775-44CC-8708-5B67F2ED70FE}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {36DF3175-0775-44CC-8708-5B67F2ED70FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {36DF3175-0775-44CC-8708-5B67F2ED70FE}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {36DF3175-0775-44CC-8708-5B67F2ED70FE}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {36DF3175-0775-44CC-8708-5B67F2ED70FE}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {FFE92053-3580-432E-981F-30657B3AF39A} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Helpers/QueryParametersExtensions.cs: -------------------------------------------------------------------------------- 1 | using SampleWebApiAspNetCore.Models; 2 | 3 | namespace SampleWebApiAspNetCore.Helpers 4 | { 5 | public static class QueryParametersExtensions 6 | { 7 | public static bool HasPrevious(this QueryParameters queryParameters) 8 | { 9 | return (queryParameters.Page > 1); 10 | } 11 | 12 | public static bool HasNext(this QueryParameters queryParameters, int totalCount) 13 | { 14 | return (queryParameters.Page < (int)GetTotalPages(queryParameters, totalCount)); 15 | } 16 | 17 | public static double GetTotalPages(this QueryParameters queryParameters, int totalCount) 18 | { 19 | return Math.Ceiling(totalCount / (double)queryParameters.PageCount); 20 | } 21 | 22 | public static bool HasQuery(this QueryParameters queryParameters) 23 | { 24 | return !String.IsNullOrEmpty(queryParameters.Query); 25 | } 26 | 27 | public static bool IsDescending(this QueryParameters queryParameters) 28 | { 29 | if (!String.IsNullOrEmpty(queryParameters.OrderBy)) 30 | { 31 | return queryParameters.OrderBy.Split(' ').Last().ToLowerInvariant().StartsWith("desc"); 32 | } 33 | return false; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/ConfigureSwaggerOptions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc.ApiExplorer; 2 | using Microsoft.Extensions.Options; 3 | using Microsoft.OpenApi.Models; 4 | using Swashbuckle.AspNetCore.SwaggerGen; 5 | 6 | namespace SampleWebApiAspNetCore 7 | { 8 | public class ConfigureSwaggerOptions : IConfigureOptions 9 | { 10 | readonly IApiVersionDescriptionProvider provider; 11 | 12 | public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) => this.provider = provider; 13 | 14 | public void Configure(SwaggerGenOptions options) 15 | { 16 | foreach (var description in provider.ApiVersionDescriptions) 17 | { 18 | options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description)); 19 | } 20 | } 21 | 22 | static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description) 23 | { 24 | var info = new OpenApiInfo() 25 | { 26 | Title = "Sample API", 27 | Version = description.ApiVersion.ToString(), 28 | Description = "A sample application with Swagger, Swashbuckle, and API versioning.", 29 | }; 30 | 31 | if (description.IsDeprecated) 32 | { 33 | info.Description += " This API version has been deprecated."; 34 | } 35 | 36 | return info; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Helpers/VersioningExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using Microsoft.AspNetCore.Mvc.Versioning; 3 | using Microsoft.Extensions.DependencyInjection; 4 | 5 | namespace SampleWebApiAspNetCore.Helpers 6 | { 7 | public static class VersioningExtension 8 | { 9 | public static void AddVersioning(this IServiceCollection services) 10 | { 11 | services.AddApiVersioning( 12 | config => 13 | { 14 | config.ReportApiVersions = true; 15 | config.AssumeDefaultVersionWhenUnspecified = true; 16 | config.DefaultApiVersion = new ApiVersion(1, 0); 17 | config.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(), 18 | new HeaderApiVersionReader("x-api-version"), 19 | new MediaTypeApiVersionReader("x-api-version")); 20 | }); 21 | services.AddVersionedApiExplorer( 22 | options => 23 | { 24 | options.GroupNameFormat = "'v'VVV"; 25 | 26 | // note: this option is only necessary when versioning by url segment. the SubstitutionFormat 27 | // can also be used to control the format of the API version in route templates 28 | options.SubstituteApiVersionInUrl = true; 29 | }); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # ASP.NET Core WebApi Sample with HATEOAS, Versioning & Swagger 2 | 3 | In this repository I want to give a plain starting point at how to build a WebAPI with ASP.NET Core. 4 | 5 | This repository contains a controller which is dealing with FoodItems. You can GET/POST/PUT/PATCH and DELETE them. 6 | 7 | Hope this helps. 8 | 9 | See the examples here: 10 | 11 | ## Versions 12 | 13 | ``` http://localhost:29435/swagger ``` 14 | 15 | ![ASPNETCOREWebAPIVersions](./.github/versions.jpg) 16 | 17 | ## GET all Foods 18 | 19 | ``` http://localhost:29435/api/v1/foods ``` 20 | 21 | ![ASPNETCOREWebAPIGET](./.github/get.jpg) 22 | 23 | ## GET single food 24 | 25 | ``` http://localhost:29435/api/v1/foods/2 ``` 26 | 27 | ![ASPNETCOREWebAPIGET](./.github/getSingle.jpg) 28 | 29 | ## POST a foodItem 30 | 31 | ``` http://localhost:29435/api/v1/foods ``` 32 | 33 | ```javascript 34 | { 35 | "name": "Lasagne", 36 | "type": "Main", 37 | "calories": 3000, 38 | "created": "2017-09-16T17:50:08.1510899+02:00" 39 | } 40 | ``` 41 | 42 | ![ASPNETCOREWebAPIGET](./.github/post.jpg) 43 | 44 | ## PUT a foodItem 45 | 46 | ``` http://localhost:29435/api/v1/foods/5 ``` 47 | 48 | ``` javascript 49 | { 50 | "name": "Lasagne2", 51 | "type": "Main", 52 | "calories": 3000, 53 | "created": "2017-09-16T17:50:08.1510899+02:00" 54 | } 55 | ``` 56 | 57 | ![ASPNETCOREWebAPIGET](./.github/put.jpg) 58 | 59 | 60 | ## PATCH a foodItem 61 | 62 | ``` http://localhost:29435/api/v1/foods/5 ``` 63 | 64 | ``` javascript 65 | [ 66 | { "op": "replace", "path": "/name", "value": "mynewname" } 67 | ] 68 | ``` 69 | 70 | ![ASPNETCOREWebAPIGET](./.github/patch.jpg) 71 | 72 | ## DELETE a foodItem 73 | 74 | ``` http://localhost:29435/api/v1/foods/5 ``` 75 | 76 | 77 | ![ASPNETCOREWebAPIGET](./.github/delete.jpg) 78 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Program.cs: -------------------------------------------------------------------------------- 1 | using Mapster; 2 | using Microsoft.AspNetCore.Mvc.ApiExplorer; 3 | using Microsoft.AspNetCore.Mvc.Infrastructure; 4 | using Microsoft.AspNetCore.Mvc.Routing; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.Extensions.Options; 7 | using Newtonsoft.Json.Serialization; 8 | using SampleWebApiAspNetCore; 9 | using SampleWebApiAspNetCore.Helpers; 10 | using SampleWebApiAspNetCore.Repositories; 11 | using SampleWebApiAspNetCore.Services; 12 | using Swashbuckle.AspNetCore.SwaggerGen; 13 | 14 | var builder = WebApplication.CreateBuilder(args); 15 | 16 | // Add services to the container. 17 | 18 | builder.Services.AddControllers() 19 | .AddNewtonsoftJson(options => 20 | options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()); 21 | 22 | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle 23 | builder.Services.AddEndpointsApiExplorer(); 24 | builder.Services.AddSwaggerGen(); 25 | 26 | builder.Services.AddCustomCors("AllowAllOrigins"); 27 | 28 | builder.Services.AddSingleton(); 29 | builder.Services.AddScoped(); 30 | builder.Services.AddScoped(typeof(ILinkService<>), typeof(LinkService<>)); 31 | builder.Services.AddTransient, ConfigureSwaggerOptions>(); 32 | 33 | builder.Services.AddSingleton(); 34 | builder.Services.AddSingleton(); 35 | 36 | builder.Services.AddRouting(options => options.LowercaseUrls = true); 37 | builder.Services.AddVersioning(); 38 | 39 | builder.Services.AddDbContext(opt => 40 | opt.UseInMemoryDatabase("FoodDatabase")); 41 | 42 | builder.Services.AddMapster(); 43 | 44 | var app = builder.Build(); 45 | 46 | var apiVersionDescriptionProvider = app.Services.GetRequiredService(); 47 | var loggerFactory = app.Services.GetRequiredService(); 48 | 49 | // Configure the HTTP request pipeline. 50 | if (app.Environment.IsDevelopment()) 51 | { 52 | app.UseSwagger(); 53 | app.UseSwaggerUI( 54 | options => 55 | { 56 | foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) 57 | { 58 | options.SwaggerEndpoint( 59 | $"/swagger/{description.GroupName}/swagger.json", 60 | description.GroupName.ToUpperInvariant()); 61 | } 62 | }); 63 | 64 | app.SeedData(); 65 | } 66 | else 67 | { 68 | app.AddProductionExceptionHandling(loggerFactory); 69 | } 70 | 71 | app.UseCors("AllowAllOrigins"); 72 | app.UseHttpsRedirection(); 73 | 74 | app.UseAuthorization(); 75 | 76 | app.MapControllers(); 77 | 78 | app.Run(); 79 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Repositories/FoodSqlRepository.cs: -------------------------------------------------------------------------------- 1 | using SampleWebApiAspNetCore.Entities; 2 | using SampleWebApiAspNetCore.Helpers; 3 | using SampleWebApiAspNetCore.Models; 4 | using System.Linq.Dynamic.Core; 5 | 6 | namespace SampleWebApiAspNetCore.Repositories 7 | { 8 | public class FoodSqlRepository : IFoodRepository 9 | { 10 | private readonly FoodDbContext _foodDbContext; 11 | 12 | public FoodSqlRepository(FoodDbContext foodDbContext) 13 | { 14 | _foodDbContext = foodDbContext; 15 | } 16 | 17 | public FoodEntity GetSingle(int id) 18 | { 19 | return _foodDbContext.FoodItems.FirstOrDefault(x => x.Id == id); 20 | } 21 | 22 | public void Add(FoodEntity item) 23 | { 24 | _foodDbContext.FoodItems.Add(item); 25 | } 26 | 27 | public void Delete(int id) 28 | { 29 | FoodEntity foodItem = GetSingle(id); 30 | _foodDbContext.FoodItems.Remove(foodItem); 31 | } 32 | 33 | public FoodEntity Update(int id, FoodEntity item) 34 | { 35 | _foodDbContext.FoodItems.Update(item); 36 | return item; 37 | } 38 | 39 | public IQueryable GetAll(QueryParameters queryParameters) 40 | { 41 | IQueryable _allItems = _foodDbContext.FoodItems.OrderBy(queryParameters.OrderBy, 42 | queryParameters.IsDescending()); 43 | 44 | if (queryParameters.HasQuery()) 45 | { 46 | _allItems = _allItems 47 | .Where(x => x.Calories.ToString().Contains(queryParameters.Query.ToLowerInvariant()) 48 | || x.Name.ToLowerInvariant().Contains(queryParameters.Query.ToLowerInvariant())); 49 | } 50 | 51 | return _allItems 52 | .Skip(queryParameters.PageCount * (queryParameters.Page - 1)) 53 | .Take(queryParameters.PageCount); 54 | } 55 | 56 | public int Count() 57 | { 58 | return _foodDbContext.FoodItems.Count(); 59 | } 60 | 61 | public bool Save() 62 | { 63 | return (_foodDbContext.SaveChanges() >= 0); 64 | } 65 | 66 | public ICollection GetRandomMeal() 67 | { 68 | List toReturn = new List(); 69 | 70 | toReturn.Add(GetRandomItem("Starter")); 71 | toReturn.Add(GetRandomItem("Main")); 72 | toReturn.Add(GetRandomItem("Dessert")); 73 | 74 | return toReturn; 75 | } 76 | 77 | private FoodEntity GetRandomItem(string type) 78 | { 79 | return _foodDbContext.FoodItems 80 | .Where(x => x.Type == type) 81 | .OrderBy(o => Guid.NewGuid()) 82 | .FirstOrDefault(); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | # DNX 42 | project.lock.json 43 | artifacts/ 44 | 45 | *_i.c 46 | *_p.c 47 | *_i.h 48 | *.ilk 49 | *.meta 50 | *.obj 51 | *.pch 52 | *.pdb 53 | *.pgc 54 | *.pgd 55 | *.rsp 56 | *.sbr 57 | *.tlb 58 | *.tli 59 | *.tlh 60 | *.tmp 61 | *.tmp_proj 62 | *.log 63 | *.vspscc 64 | *.vssscc 65 | .builds 66 | *.pidb 67 | *.svclog 68 | *.scc 69 | 70 | # Chutzpah Test files 71 | _Chutzpah* 72 | 73 | # Visual C++ cache files 74 | ipch/ 75 | *.aps 76 | *.ncb 77 | *.opensdf 78 | *.sdf 79 | *.cachefile 80 | 81 | # Visual Studio profiler 82 | *.psess 83 | *.vsp 84 | *.vspx 85 | 86 | # TFS 2012 Local Workspace 87 | $tf/ 88 | 89 | # Guidance Automation Toolkit 90 | *.gpState 91 | 92 | # ReSharper is a .NET coding add-in 93 | _ReSharper*/ 94 | *.[Rr]e[Ss]harper 95 | *.DotSettings.user 96 | 97 | # JustCode is a .NET coding add-in 98 | .JustCode 99 | 100 | # TeamCity is a build add-in 101 | _TeamCity* 102 | 103 | # DotCover is a Code Coverage Tool 104 | *.dotCover 105 | 106 | # NCrunch 107 | _NCrunch_* 108 | .*crunch*.local.xml 109 | 110 | # MightyMoose 111 | *.mm.* 112 | AutoTest.Net/ 113 | 114 | # Web workbench (sass) 115 | .sass-cache/ 116 | 117 | # Installshield output folder 118 | [Ee]xpress/ 119 | 120 | # DocProject is a documentation generator add-in 121 | DocProject/buildhelp/ 122 | DocProject/Help/*.HxT 123 | DocProject/Help/*.HxC 124 | DocProject/Help/*.hhc 125 | DocProject/Help/*.hhk 126 | DocProject/Help/*.hhp 127 | DocProject/Help/Html2 128 | DocProject/Help/html 129 | 130 | # Click-Once directory 131 | publish/ 132 | 133 | # Publish Web Output 134 | *.[Pp]ublish.xml 135 | *.azurePubxml 136 | ## TODO: Comment the next line if you want to checkin your 137 | ## web deploy settings but do note that will include unencrypted 138 | ## passwords 139 | #*.pubxml 140 | 141 | *.publishproj 142 | 143 | # NuGet Packages 144 | *.nupkg 145 | # The packages folder can be ignored because of Package Restore 146 | **/packages/* 147 | # except build/, which is used as an MSBuild target. 148 | !**/packages/build/ 149 | # Uncomment if necessary however generally it will be regenerated when needed 150 | #!**/packages/repositories.config 151 | 152 | # Windows Azure Build Output 153 | csx/ 154 | *.build.csdef 155 | 156 | # Windows Store app package directory 157 | AppPackages/ 158 | 159 | # Visual Studio cache files 160 | # files ending in .cache can be ignored 161 | *.[Cc]ache 162 | # but keep track of directories ending in .cache 163 | !*.[Cc]ache/ 164 | 165 | # Others 166 | ClientBin/ 167 | [Ss]tyle[Cc]op.* 168 | ~$* 169 | *~ 170 | *.dbmdl 171 | *.dbproj.schemaview 172 | *.pfx 173 | *.publishsettings 174 | node_modules/ 175 | orleans.codegen.cs 176 | 177 | # RIA/Silverlight projects 178 | Generated_Code/ 179 | 180 | # Backup & report files from converting an old project file 181 | # to a newer Visual Studio version. Backup files are not needed, 182 | # because we have git ;-) 183 | _UpgradeReport_Files/ 184 | Backup*/ 185 | UpgradeLog*.XML 186 | UpgradeLog*.htm 187 | 188 | # SQL Server files 189 | *.mdf 190 | *.ldf 191 | 192 | # Business Intelligence projects 193 | *.rdl.data 194 | *.bim.layout 195 | *.bim_*.settings 196 | 197 | # Microsoft Fakes 198 | FakesAssemblies/ 199 | 200 | # Node.js Tools for Visual Studio 201 | .ntvs_analysis.dat 202 | 203 | # Visual Studio 6 build log 204 | *.plg 205 | 206 | # Visual Studio 6 workspace options file 207 | *.opt 208 | 209 | # LightSwitch generated files 210 | GeneratedArtifacts/ 211 | _Pvt_Extensions/ 212 | ModelManifest.xml 213 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Services/LinkService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using SampleWebApiAspNetCore.Models; 3 | using SampleWebApiAspNetCore.Helpers; 4 | using System.Reflection; 5 | using Microsoft.AspNetCore.Mvc.Routing; 6 | using Microsoft.AspNetCore.Mvc.Infrastructure; 7 | 8 | namespace SampleWebApiAspNetCore.Services 9 | { 10 | public class LinkService : ILinkService 11 | { 12 | private readonly IUrlHelper _urlHelper; 13 | 14 | public LinkService(IUrlHelperFactory urlHelperFactory, IActionContextAccessor actionContextAccessor) 15 | { 16 | _urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext); 17 | } 18 | 19 | public List CreateLinksForCollection(QueryParameters queryParameters, int totalCount, ApiVersion version) 20 | { 21 | Type controllerType = (typeof(T)); 22 | MethodInfo[] methods = controllerType.GetMethods(); 23 | 24 | var links = new List(); 25 | var getAllMethodName = GetMethod(methods, typeof(HttpGetAttribute), 0); 26 | 27 | // self 28 | links.Add(new LinkDto(_urlHelper.Link(getAllMethodName, new 29 | { 30 | pagecount = queryParameters.PageCount, 31 | page = queryParameters.Page, 32 | orderby = queryParameters.OrderBy 33 | }), "self", "GET")); 34 | 35 | links.Add(new LinkDto(_urlHelper.Link(getAllMethodName, new 36 | { 37 | pagecount = queryParameters.PageCount, 38 | page = 1, 39 | orderby = queryParameters.OrderBy 40 | }), "first", "GET")); 41 | 42 | links.Add(new LinkDto(_urlHelper.Link(getAllMethodName, new 43 | { 44 | pagecount = queryParameters.PageCount, 45 | page = queryParameters.GetTotalPages(totalCount), 46 | orderby = queryParameters.OrderBy 47 | }), "last", "GET")); 48 | 49 | if (queryParameters.HasNext(totalCount)) 50 | { 51 | links.Add(new LinkDto(_urlHelper.Link(getAllMethodName, new 52 | { 53 | pagecount = queryParameters.PageCount, 54 | page = queryParameters.Page + 1, 55 | orderby = queryParameters.OrderBy 56 | }), "next", "GET")); 57 | } 58 | 59 | if (queryParameters.HasPrevious()) 60 | { 61 | links.Add(new LinkDto(_urlHelper.Link(getAllMethodName, new 62 | { 63 | pagecount = queryParameters.PageCount, 64 | page = queryParameters.Page - 1, 65 | orderby = queryParameters.OrderBy 66 | }), "previous", "GET")); 67 | } 68 | 69 | var posturl = _urlHelper.Link(GetMethod(methods, typeof(HttpPostAttribute)), new { version = version.ToString() }); 70 | 71 | links.Add( 72 | new LinkDto(posturl, 73 | "create", 74 | "POST")); 75 | 76 | return links; 77 | } 78 | 79 | public object ExpandSingleFoodItem(object resource, int identifier, ApiVersion version) 80 | { 81 | var resourceToReturn = resource.ToDynamic() as IDictionary; 82 | 83 | var links = GetLinksForSingleItem(identifier, version); 84 | 85 | resourceToReturn.Add("links", links); 86 | 87 | return resourceToReturn; 88 | } 89 | 90 | 91 | private IEnumerable GetLinksForSingleItem(int id, ApiVersion version) 92 | { 93 | Type myType = (typeof(T)); 94 | MethodInfo[] methods = myType.GetMethods(); 95 | var links = new List(); 96 | 97 | var getLink = _urlHelper.Link(GetMethod(methods, typeof(HttpGetAttribute), 1), new { version = version.ToString(), id = id }); 98 | links.Add(new LinkDto(getLink, "self", "GET")); 99 | 100 | var deleteLink = _urlHelper.Link(GetMethod(methods, typeof(HttpDeleteAttribute)), new { version = version.ToString(), id = id }); 101 | links.Add( 102 | new LinkDto(deleteLink, 103 | "delete", 104 | "DELETE")); 105 | 106 | var createLink = _urlHelper.Link(GetMethod(methods, typeof(HttpPostAttribute)), new { version = version.ToString() }); 107 | links.Add( 108 | new LinkDto(createLink, 109 | "create_food", 110 | "POST")); 111 | 112 | var updateLink = _urlHelper.Link(GetMethod(methods, typeof(HttpPutAttribute)), new { version = version.ToString(), id = id }); 113 | links.Add( 114 | new LinkDto(updateLink, 115 | "update_food", 116 | "PUT")); 117 | 118 | return links; 119 | } 120 | 121 | private string GetMethod(MethodInfo[] methods, Type type, int routeParamsLength = 0) 122 | { 123 | var filteredMethods = methods.Where(m => m.GetCustomAttributes(type, false).Length > 0).ToArray(); 124 | 125 | if (filteredMethods.Length == 0) 126 | { 127 | return ""; 128 | } 129 | 130 | if (routeParamsLength == 0) 131 | { 132 | var toReturn = filteredMethods.FirstOrDefault(); 133 | 134 | return toReturn is not null ? toReturn.Name : ""; 135 | } 136 | 137 | foreach (var method in filteredMethods) 138 | { 139 | var routeAttribs = method.GetCustomAttributes(typeof(RouteAttribute)); 140 | 141 | if (routeAttribs.Count() == routeParamsLength) 142 | { 143 | return method.Name; 144 | } 145 | } 146 | 147 | return ""; 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /SampleWebApiAspNetCore/Controllers/v1/FoodsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.JsonPatch; 2 | using Microsoft.AspNetCore.Mvc; 3 | using SampleWebApiAspNetCore.Dtos; 4 | using SampleWebApiAspNetCore.Entities; 5 | using SampleWebApiAspNetCore.Helpers; 6 | using SampleWebApiAspNetCore.Services; 7 | using SampleWebApiAspNetCore.Models; 8 | using SampleWebApiAspNetCore.Repositories; 9 | using System.Text.Json; 10 | using MapsterMapper; 11 | 12 | namespace SampleWebApiAspNetCore.Controllers.v1 13 | { 14 | [ApiController] 15 | [ApiVersion("1.0")] 16 | [Route("api/v{version:apiVersion}/[controller]")] 17 | public class FoodsController : ControllerBase 18 | { 19 | private readonly IFoodRepository _foodRepository; 20 | private readonly IMapper _mapper; 21 | private readonly ILinkService _linkService; 22 | 23 | public FoodsController( 24 | IFoodRepository foodRepository, 25 | IMapper mapper, 26 | ILinkService linkService) 27 | { 28 | _foodRepository = foodRepository; 29 | _mapper = mapper; 30 | _linkService = linkService; 31 | } 32 | 33 | [HttpGet(Name = nameof(GetAllFoods))] 34 | public ActionResult GetAllFoods(ApiVersion version, [FromQuery] QueryParameters queryParameters) 35 | { 36 | List foodItems = _foodRepository.GetAll(queryParameters).ToList(); 37 | 38 | var allItemCount = _foodRepository.Count(); 39 | 40 | var paginationMetadata = new 41 | { 42 | totalCount = allItemCount, 43 | pageSize = queryParameters.PageCount, 44 | currentPage = queryParameters.Page, 45 | totalPages = queryParameters.GetTotalPages(allItemCount) 46 | }; 47 | 48 | Response.Headers.Add("X-Pagination", JsonSerializer.Serialize(paginationMetadata)); 49 | 50 | var links = _linkService.CreateLinksForCollection(queryParameters, allItemCount, version); 51 | var toReturn = foodItems.Select(x => _linkService.ExpandSingleFoodItem(x, x.Id, version)); 52 | 53 | return Ok(new 54 | { 55 | value = toReturn, 56 | links = links 57 | }); 58 | } 59 | 60 | [HttpGet] 61 | [Route("{id:int}", Name = nameof(GetSingleFood))] 62 | public ActionResult GetSingleFood(ApiVersion version, int id) 63 | { 64 | FoodEntity foodItem = _foodRepository.GetSingle(id); 65 | 66 | if (foodItem == null) 67 | { 68 | return NotFound(); 69 | } 70 | 71 | FoodDto item = _mapper.Map(foodItem); 72 | 73 | return Ok(_linkService.ExpandSingleFoodItem(item, item.Id, version)); 74 | } 75 | 76 | [HttpPost(Name = nameof(AddFood))] 77 | public ActionResult AddFood(ApiVersion version, [FromBody] FoodCreateDto foodCreateDto) 78 | { 79 | if (foodCreateDto == null) 80 | { 81 | return BadRequest(); 82 | } 83 | 84 | FoodEntity toAdd = _mapper.Map(foodCreateDto); 85 | 86 | _foodRepository.Add(toAdd); 87 | 88 | if (!_foodRepository.Save()) 89 | { 90 | throw new Exception("Creating a fooditem failed on save."); 91 | } 92 | 93 | FoodEntity newFoodItem = _foodRepository.GetSingle(toAdd.Id); 94 | FoodDto foodDto = _mapper.Map(newFoodItem); 95 | 96 | return CreatedAtRoute(nameof(GetSingleFood), 97 | new { version = version.ToString(), id = newFoodItem.Id }, 98 | _linkService.ExpandSingleFoodItem(foodDto, foodDto.Id, version)); 99 | } 100 | 101 | [HttpPatch("{id:int}", Name = nameof(PartiallyUpdateFood))] 102 | public ActionResult PartiallyUpdateFood(ApiVersion version, int id, [FromBody] JsonPatchDocument patchDoc) 103 | { 104 | if (patchDoc == null) 105 | { 106 | return BadRequest(); 107 | } 108 | 109 | FoodEntity existingEntity = _foodRepository.GetSingle(id); 110 | 111 | if (existingEntity == null) 112 | { 113 | return NotFound(); 114 | } 115 | 116 | FoodUpdateDto foodUpdateDto = _mapper.Map(existingEntity); 117 | patchDoc.ApplyTo(foodUpdateDto); 118 | 119 | TryValidateModel(foodUpdateDto); 120 | 121 | if (!ModelState.IsValid) 122 | { 123 | return BadRequest(ModelState); 124 | } 125 | 126 | _mapper.Map(foodUpdateDto, existingEntity); 127 | FoodEntity updated = _foodRepository.Update(id, existingEntity); 128 | 129 | if (!_foodRepository.Save()) 130 | { 131 | throw new Exception("Updating a fooditem failed on save."); 132 | } 133 | 134 | FoodDto foodDto = _mapper.Map(updated); 135 | 136 | return Ok(_linkService.ExpandSingleFoodItem(foodDto, foodDto.Id, version)); 137 | } 138 | 139 | [HttpDelete] 140 | [Route("{id:int}", Name = nameof(RemoveFood))] 141 | public ActionResult RemoveFood(int id) 142 | { 143 | FoodEntity foodItem = _foodRepository.GetSingle(id); 144 | 145 | if (foodItem == null) 146 | { 147 | return NotFound(); 148 | } 149 | 150 | _foodRepository.Delete(id); 151 | 152 | if (!_foodRepository.Save()) 153 | { 154 | throw new Exception("Deleting a fooditem failed on save."); 155 | } 156 | 157 | return NoContent(); 158 | } 159 | 160 | [HttpPut] 161 | [Route("{id:int}", Name = nameof(UpdateFood))] 162 | public ActionResult UpdateFood(ApiVersion version, int id, [FromBody] FoodUpdateDto foodUpdateDto) 163 | { 164 | if (foodUpdateDto == null) 165 | { 166 | return BadRequest(); 167 | } 168 | 169 | var existingFoodItem = _foodRepository.GetSingle(id); 170 | 171 | if (existingFoodItem == null) 172 | { 173 | return NotFound(); 174 | } 175 | 176 | _mapper.Map(foodUpdateDto, existingFoodItem); 177 | 178 | _foodRepository.Update(id, existingFoodItem); 179 | 180 | if (!_foodRepository.Save()) 181 | { 182 | throw new Exception("Updating a fooditem failed on save."); 183 | } 184 | 185 | FoodDto foodDto = _mapper.Map(existingFoodItem); 186 | 187 | return Ok(_linkService.ExpandSingleFoodItem(foodDto, foodDto.Id, version)); 188 | } 189 | 190 | [HttpGet("GetRandomMeal", Name = nameof(GetRandomMeal))] 191 | public ActionResult GetRandomMeal() 192 | { 193 | ICollection foodItems = _foodRepository.GetRandomMeal(); 194 | 195 | IEnumerable dtos = foodItems.Select(x => _mapper.Map(x)); 196 | 197 | var links = new List(); 198 | 199 | // self 200 | links.Add(new LinkDto(Url.Link(nameof(GetRandomMeal), null), "self", "GET")); 201 | 202 | return Ok(new 203 | { 204 | value = dtos, 205 | links = links 206 | }); 207 | } 208 | } 209 | } 210 | --------------------------------------------------------------------------------