Thursday October 17th, 2019

ASP.NET Web API

By Ebubekir Sezer

Hello, When we develop an application, we may want to keep data in the local or real time databases. In my previous articles, I wrote about the how to use sqlite. Now, I would like to create a web api using by the ASP.NET. While writing this article, I follow the Microsoft Documentation.

Firstly, I created a blank solution and then i added the ASP.NET Core Web Application project and i choose the type of the project API. I gave the project name XamarinDBService. After the creating project, I created a folder which name is Models. In the Models folder, I added two classes. These are Entity and Person class. In the Entity class, I keep the ID. I created Entity class because i do not want to write all the time ID property for that reason, i inherited the other class from entity. In the Person class, I keep the Name and Surname.

namespace XamarinDBService.Models
{
    public class Entity
    {
        public string ID { get; set; } = Guid.NewGuid().ToString();
    }
}
namespace XamarinDBService.Models
{
    public class Person : Entity
    {
        public string Name { get; set; }
        public string Surname { get; set; }
    }
}

After the creating models, We should add the some packages. These are Microsoft. EntityFrameworkCore. SqlServer and Microsoft.EntityFrameworkCore.InMemory.

Now, We should create a PersonContext class under the Models folder. This PersonContext class will be inherited from the DBContext. We should write the these codes;

namespace XamarinDBService.Models
{
    public class PersonContext : DbContext
    {
        public PersonContext(DbContextOptions<PersonContext> options) : base(options)
        {

        }
        public DbSet<Person> People { get; set; }
    }
}

After the adding above codes, We should go the Startup.cs and wrote these codes in the ConfigureServices function.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<PersonContext>(opt => opt.UseInMemoryDatabase("PeopleList"));

            services.AddControllers();
        }

For the make CRUD operations, we should add the controllers. Click right of the mouse on the Controller folder and add new controller. This controller type must be API Controller with actions, using Entity Framework. We should choose the model class Person and data context PersonContext and then click add.

In the PeopleController, We should add the nameof before the GetPerson and then our web api will be done.

return CreatedAtAction(nameof(GetPerson), new { id = person.ID }, person);

Using with the Postman, We can make the Get, Post, Update and Delete operations.

We should be sure that our web service work in the local url and then we should publish it. For the publish service, Click right on the project and publish and then create a AppService then you can publish it.

I will be happy, if you ask your questions via e-mail or comments.