قالب وردپرس درنا توس
Home / Tips and Tricks / How to get started with ASP.NET for API Development – CloudSavvy IT

How to get started with ASP.NET for API Development – CloudSavvy IT



asp.net

ASP.NET is a platform for building web APIs with C # and .NET. It is often used for app backends and can automatically serial classes to JSON. We go through creating a service that talks to a database and stores a list of objects.

Create a project

We use Visual Studio, as it provides excellent .NET support instantly. Create a new project using the “ASP.NET Core Web Application”

; template:

create new project

Give it a name and select “API”, as we are not building an ASP.NET frontend here.

select API

This initiates your solution with all the headboards needed to get a basic API up and running. If you click the run button (labeled IIS Express, which launches an IIS Web server), you will see the API that displays dummy weather data.

start program

dummy data

We use this database to create a simple API that connects to a database and reads and writes custom objects. In this case, it is a collection of user data, but the API will largely work the same for more complicated device models.

Connect a database

It is a good idea to divide the logic for handling queries and the logic for managing to talk to the database. We create a database service with some reading and writing functions, then an API controller that responds to requests by talking to the database service. The first thing you should do, however, is that ASP.NET talks to a database in the first place.

We need to install some packages to work with a database. Click Tools> NuGet Package Manager and select “Manage NuGet Packages for Solution.”

install nugest package

If you use an SQL database, the database connection is managed with specific plugin packages that implement EntityFrameworkCore for the underlying database. This is a framework that maps C # objects to a relational database and allows you to use LINQ queries and other built-in tools to interact with it. You will find a complete list of database providers here for the most popular relational databases.

We will join MongoDB here, as NoSQL document databases are translated into one List quite seamlessly, and the MongoDB driver supports LINQ issues like EF Core.

Install the MongoDB.Driver package:

Installs the MongoDB.Driver package

Create a new folder at the root of your project called “Models”. In it, you create a device model called User.cs, which is the schedule for the collection stored in the database. You can use [BsonId] and [BsonRepresentation(BsonType.ObjectId)] attribute to tell the MongoDB driver that this ID string should be interpreted as a collective ID and can be sent as string although Mongo internally wants type ObjectId.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;

namespace ExampleService.Models
{
    public class User
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        
        [BsonElement("Name")]
        public string Name { get; set; }
        public string Email { get; set; }
        // etc...
    }
}

In the same folder, create a file named DatabaseSettings.cs, which stores a class and an interface for the database settings.

namespace ExampleService.Models
{
    public class ExampleDatabaseSettings : IExampleDatabaseSettings
    {
        public string ExampleCollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }

    public interface IExampleDatabaseSettings
    { 
        string ExampleCollectionName { get; set; }
        string ConnectionString { get; set; }
        string DatabaseName { get; set; }
    }
}

We can fill in these property values appsettings.json, by adding the following configuration:

"ExampleDatabaseSettings": {
    "ExampleCollectionName": "Users",
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "Example"
}

You will of course need to create or rename Example database and create Users collection in it.

Finally, we add some code in Startup.cs in ConfigureServices method, which retrieves the settings from appsettings.json file and register the interface via Dependency Injection:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure(
      Configuration.GetSection(nameof(ExampleDatabaseSettings)));

    services.AddSingleton(sp =>
      sp.GetRequiredService>().Value);

    services.AddControllers();
}

You must add a directive at the top with your model name.

Write a CRUD database service

When the database is connected, you can add the service to talk. The following class contains one IMongoCollection which represents the MongoDB collection in a format that C # can easily interact with. Reading, writing, updating and deleting directly affect the underlying collection.

The constructor method takes the database settings, starts a new client, retrieves the database and then initializes _users collection.

using ExampleService.Models;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Linq;

namespace ExampleService.Services
{
    public class ExampleService
    {
        private readonly IMongoCollection _users;

        public UserService(IExampleDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            _users = database.GetCollection(settings.ExampleCollectionName);
        }

        public List Get() =>
            _users.Find(user => true).ToList();

        public User Get(string id) =>
            _users.Find(user => user.Id == id).FirstOrDefault();

        public User Create(User user)
        {
            _users.InsertOne(user);
            return user;
        }

        public void Update(string id, User userIn) =>
            _users.ReplaceOne(user=> user.Id == id, userIn);

        public void Remove(User userIn) =>
            _users.DeleteOne(user => user.Id == userIn.Id);

        public void Remove(string id) => 
            _users.DeleteOne(user=> user.Id == id);
    }
}

The rest of the class is simply a set of CRUD operations for interaction with the database. Feel free to use any custom logic here.

Back in Startup.cs, you want to add this as a startup service:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure(
      Configuration.GetSection(nameof(ExampleDatabaseSettings)));

    services.AddSingleton(sp =>
      sp.GetRequiredService>().Value);

    services.AddSingleton();

    services.AddControllers();
}

You need another one again using Directive, this time for ExampleService.Services.

Configure an API controller

Then you need a controller to manage API actions. Fortunately, Visual Studio makes it easy; You can right-click on “Controllers” to add a new controller with read / write operations. This creates a new control unit with some basic methods.

Right click

The route is defined at the top. By default, this is set to /api/controller, where controller is the controller name (minus the “Controller” part). You can change this if you want, but this is a good pattern for most people.

[Route("api/[controller]")]

You want to add a reference to your database service at the top of the class and fill it in the constructor:

private readonly ExampleService _exampleService;

public ExampleController(ExampleService exampleService)
{
    _exampleService = exampleService;
}

You want to change the HttpGet method to return one ActionResult> of the schedule you store. (Of course, you need to add a reference to your model name.) ActionResult is a dynamic type that wraps either TV values ​​inside it or an HTTP response result.

[HttpGet]
public ActionResult> Get()
{
    return _exampleService.Get();
}

If you want to add another Get method but on a different route, you can pass it as a parameter in the attribute:

[HttpGet("otherroute")]
public ActionResult> GetSomeThingElse()
{
    return _exampleService.GetSomeThingElse();
}

For the HttpPost method, then call the Create method for your database service and return CreatedAtRoute, which sends a 201 response to the client and informs them that the creation of objects was successful.

[HttpPost]
public ActionResult Create(User userIn)
{
    _exampleService.Create(userIn);

    return CreatedAtRoute("GetUser", new { id = userIn.Id.ToString() }, userIn);
}

For the other routes, you can configure them as you wish. The general idea is to manage the user input, perform validations you need, and call the correct database actions, return the user to something useful or a status code that tells what happened.

At this point, however, you should be able to press the IIS Express Run button at the top and test the API. By default, this route is the weather service’s API that came with the tablet, so instead of printing it each time, you can change the troubleshooting path under Project> Properties> Troubleshooting and change the Start Browser option.

change troubleshooting path

When you want to test on a remote server, you can create a production building from Build> Publish Service. Select file output and edit the configuration according to your needs. For example, you can choose to build as standalone, which will package all .NET dependencies with build, and also to publish as a single executable. You can also change the finish time here.

settings for production building

If you want to publish to Linux, you need to add a runtime identifier to yours .csproj file.

linux-x64

Of course, the API shown here is insecure. ASP.NET has a fantastic authentication system that offers support for JWT-based tokens and can be configured to work with OAuth providers such as Google and Facebook.


Source link