0% found this document useful (0 votes)
208 views

Corer 2.2

The document describes an ASP.NET Core REST API tutorial that covers setting up and configuring Swagger, implementing versioning, dependency injection, and creating, retrieving, updating and deleting resources. It includes code examples for setting up the API project structure, controllers, services, models and routes. Key steps covered are configuring Swagger UI, creating API versions, registering services via dependency injection, and building CRUD operations for a post resource.

Uploaded by

samer_mf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
208 views

Corer 2.2

The document describes an ASP.NET Core REST API tutorial that covers setting up and configuring Swagger, implementing versioning, dependency injection, and creating, retrieving, updating and deleting resources. It includes code examples for setting up the API project structure, controllers, services, models and routes. Key steps covered are configuring Swagger UI, creating API versions, registering services via dependency injection, and building CRUD operations for a post resource.

Uploaded by

samer_mf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

ASP.NET CORE 2.

2 & 3 REST API TUTORIAL

HTTPS://WWW.YOUTUBE.COM/PLAYLIST?LIST=PL UOEQUMGNXXOGMSDWU7TL 6IQTSOTYJTWU

TABLE OF CONTENTS
https://www.youtube.com/playlist?list=PLUOequmGnXxOgmSDWU7Tl6iQTsOtyjtwU ........................................... 1
ASP.NET Core 2.2 REST API Tutorial 1 - Setup and Swagger configuration ................................................................... 2
ASP.NET Core 2.2 REST API Tutorial 2 - Implementing versioning................................................................................. 4
ASP.NET Core 2.2 REST API Tutorial 3 - Dependency injection and clean service registration ..................................... 5
ASP.NET Core 3 & 2.2 REST API Tutorial 4 - Creating resources using POST ................................................................. 7
ASP.NET Core 3 & 2.2 REST API Tutorial 5 - Retrieving resources with GET .................................................................. 8
ASP.NET Core 2.2 REST API Tutorial 6 - Updating resources with PUT ........................................................................ 11
ASP.NET Core 3 & 2.2 REST API Tutorial 7 - Deleting resources with DELETE ............................................................. 12
ASP.NET CORE 2.2 REST API TUTORIAL 1 - SETUP AND SWAGGER CONFIGURATION

Delete IIS express from properties

Add swagger SWASHBUCKLE.ASPNETCO RE


Add folder Options, create class SwaggerOptions.cs
public class SwaggerOptions
{

public string JsonRoute { get; set; }


public string Description { get; set; }
public string UiEndpoint { get; set; }
}

Add to startup the following code


var swaggerOptions = new SwaggerOptions();
Configuration.GetSection(nameof(SwaggerOptions)).Bind(swaggerOptions);

app.UseSwagger(option => { option.RouteTemplate = swaggerOptions.JsonRoute; });


app.UseSwaggerUI(option =>
{
option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description);
});
ASP.NET CORE 2.2 REST API TUTORIAL 2 - IMPLEMENTING VERSIONING

Create folder Domain, create class Post.cs

public class Post


{
public string Id { get; set; }
}

Create Controllers/api/v1, create class PostsController.cs

public class PostsController : Controller


{
private List<Post> _posts;

public PostsController()
{
_posts = new List<Post>();
for (var i = 0; i < 5; i++)
{
_posts.Add(new Post{Id = Guid.NewGuid().ToString()});
}
}

[HttpGet(ApiRoutes.Posts.GetAll)]
public IActionResult GetAll()
{
return Ok(_posts);
}

Create folder Contract, create class Contract/v1/ApiRouters.cs

public static class ApiRoutes


{
public const string Root = "api";
public const string Version = "v1";
public const string Base = Root + "/" + Version;

public static class Posts


{
public const string GetAll = Base+"/posts";
public const string Create = Base + "/posts";
public const string Get = Base + "/posts/{postId}";

}
}
ASP.NET CORE 2.2 REST API TUTORIAL 3 - DEPENDENCY INJECTION AND CLEAN SERVICE
REGISTRATION

Create folder Installers, create interface IInstaller.cs


public interface IInstaller
{
void InstallServices(IServiceCollection services , IConfiguration configuration);

Create class MvcInstaller.cs which implements IInstaller interface


public class MvcInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given
request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new Info { Title = "Tweetbook API", Version = "v1" });
});
}
}

Create class MvcInstaller.cs which implements IInstaller interface


public class DbInstaller :IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection")));
}
}
Create class InstallerExtensions.cs
public static class InstallerExtensions
{
public static void InstallServicesInAssemble(this IServiceCollection services, IConfiguration
configuration)
{
var installers = typeof(Startup).Assembly.ExportedTypes.Where(x =>
typeof(IInstaller).IsAssignableFrom(x) && !x.IsInterface &&
!x.IsAbstract).Select(Activator.CreateInstance).Cast<IInstaller>().ToList();
installers.ForEach(installer => installer.InstallServices(services, configuration));

Remove from method ConfigureService from startup.cs and make it:


// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.InstallServicesInAssemble(Configuration);
}
ASP.NET CORE 3 & 2.2 REST API TUTORIAL 4 - CREATING RESOURCES USING POST

Create new folders Contract/v1/Requests and Contract/v1/Responses

Create new class Contract/v1/Requests/CreatePostRequest.cs


public class CreatePostRequest
{
public string Id { get; set; }
}

Create new class Contract/v1/Responses/PostResponse.cs


public class PostResponse
{
public string Id { get; set; }
}

Add new method to PostsController.cs


[HttpPost(ApiRoutes.Posts.Create)]
public IActionResult Create([FromBody] CreatePostRequest postRequest)
{
var post = new Post{Id=postRequest.Id};

if (string.IsNullOrEmpty(post.Id))
post.Id = Guid.NewGuid().ToString();

_posts.Add(post);

var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}";


var locationUri = baseUrl + "/" + ApiRoutes.Posts.Get.Replace("{postId}", post.Id);
var response = new PostResponse {Id = post.Id};
return Created(locationUri, response);
}
ASP.NET CORE 3 & 2.2 REST API TUTORIAL 5 - RETRIEVING RESOURCES WITH GET

Modify Post.cs, add string name, and make Id Guid


public class Post
{
public Guid Id { get; set; }
public string Name { get; set; }
}

Modify CreatePostRequest.cs make Id Guid


public class CreatePostRequest
{
public Guid Id { get; set; }
}

Modify PostResponse.cs make Id Guid


public class PostResponse
{
public Guid Id { get; set; }
}

Create Services folder, add IPostService.cs interface


public interface IPostService

List<Post> GetPosts();

Post GetPostById(Guid postId);

}
Add PostService.cs class which implements IPostService interface
public class PostService : IPostService
{
private readonly List<Post> _posts;

public PostService()
{
_posts = new List<Post>();
for (var i = 0; i < 5; i++)
{
_posts.Add(new Post
{
Id = Guid.NewGuid(),
Name = $"Post Name {i}"
});
}
}
public List<Post> GetPosts()
{
return _posts;
}

public Post GetPostById(Guid postId)


{
return _posts.SingleOrDefault(x => x.Id == postId);

}
}

Modify DBInstaller.cs (which was created instead of startup.cs) and add AddSingleton method
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
configuration.GetConnectionString("DefaultConnection")));

services.AddSingleton<IPostService, PostService>();
}
Modify PostsController.cs, as follows
public class PostsController : Controller
{

private readonly IPostService _postService;

public PostsController(IPostService postService)


{
_postService = postService;
}

[HttpGet(ApiRoutes.Posts.GetAll)]
public IActionResult GetAll()
{
return Ok(_postService.GetPosts());
}

[HttpGet(ApiRoutes.Posts.Get)]
public IActionResult Get([FromRoute] Guid postId)
{
var post = _postService.GetPostById(postId);
if (post == null)
return NotFound();
return Ok(post);
}

[HttpPost(ApiRoutes.Posts.Create)]
public IActionResult Create([FromBody] CreatePostRequest postRequest)
{
var post = new Post{Id = postRequest.Id};

if (post.Id != Guid.Empty)
post.Id = Guid.NewGuid();

_postService.GetPosts().Add(post);

var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}";


var locationUri = baseUrl + "/" + ApiRoutes.Posts.Get.Replace("{postId}", post.Id.ToString());
var response = new PostResponse {Id = post.Id};
return Created(locationUri, response);
}

}
ASP.NET CORE 2.2 REST API TUTORIAL 6 - UPDATING RESOURCES W ITH PUT

Add Contract/v1/Requests/ class UpdatePostRequest.cs


public class UpdatePostRequest
{
public string Name { get; set; }
}

Modify interface IPostService.cs add UpdatePost method


public interface IPostService
{
List<Post> GetPosts();
Post GetPostById(Guid postId);
bool UpdatePost(Post postToUpdate);

Modify PostService.cs, add updatePost method


public bool UpdatePost(Post postToUpdate)
{
var exists = GetPostById(postToUpdate.Id) != null;
if (!exists)
return false;
var index = _posts.FindIndex(x => x.Id == postToUpdate.Id);
_posts[index] = postToUpdate;
return true;

Modify ApiRoutes.cs, add Update static method


public const string Update = Base + "/posts/{postId}";

Modify PostsController.cs, add Update method

[HttpPut(ApiRoutes.Posts.Update)]
public IActionResult Update([FromRoute] Guid postId, [FromBody] UpdatePostRequest request)
{
var post = new Post
{
Id = postId,
Name = request.Name
};
var updated = _postService.UpdatePost(post);
if (!updated)
return NotFound();
return Ok(post);
}
ASP.NET CORE 3 & 2.2 REST API TUTORIAL 7 - DELETING RESOURCES W ITH DELETE

Modify interface IPostService.cs add DeletePost method


public interface IPostService
{
List<Post> GetPosts();
Post GetPostById(Guid postId);
bool UpdatePost(Post postToUpdate);
bool DeletePost(Guid postId);

Modify PostService.cs, add updatePost method


public bool DeletePost(Guid postId)
{
var post= GetPostById(postId);
if(post == null)
return false;
_posts.Remove(post);
return true;
}

Modify ApiRoutes.cs, add Update static method


public const string Delete = Base + "/posts/{postId}";

Modify PostsController.cs, add Delete method

[HttpDelete(ApiRoutes.Posts.Delete)]
public IActionResult Delete([FromRoute] Guid postId)
{
var isDeleted = _postService.DeletePost(postId);
if (!isDeleted)
return NotFound();
return NoContent();
}

You might also like