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

Getting started with ASP.NET for API development – CloudSavvy IT



asp.net

ASP.NET is a platform for building web APIs using C # and .NET. It is widely used for app backends and can automatically serialize classes to JSON. We are going to set up a service that communicates with a database and stores a list of objects.

Create a project

We’ll be using Visual Studio because it has great .NET support right away. Create a new project using the ASP.NET Core Web Application template:

create new project

Give it a name and select “API”, as no ASP.NET frontend is created here.

Select API

This will initialize your solution with all the necessary boiler plates to get a basic API up and running. When you hit the Run button (labeled IIS Express, which starts an IIS web server), the API shows some dummy data about the weather.

Start the program

Dummy data

We’re going to use this base to set up a simple API that connects to a database and reads and writes custom objects. In this case, it’s a collection of user data, but the API works much the same for more complicated entity models.

Connecting a database

It is a good idea to split the logic of processing requests and the logic of processing conversations with the database. We’ll create a database service with some read and write functionality and then an API controller that will respond to requests by talking to the database service. The first thing you need to do is ASP.NET primarily to communicate with a database.

We have to install some packages in order to work with a database. Click Tools> NuGet Package Manager and select Manage NuGet Packages For Solution.

Install the nugest packages

When using a SQL database, the database connection is handled with certain plug-in 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 native tools to interact with it. A full list of database providers for the most popular relational databases is available here.

We will be working with MongoDB here as NoSQL document databases are translated to a List pretty seamless, and the MongoDB driver supports LINQ queries much like EF Core does.

Install the MongoDB.Driver package:

Install the MongoDB.Driver package

Create a new folder named Models in the root of your project. Inside, create an entity model named User.csThis is the schema for the collection that will be stored in the database. You can use the … [BsonId] and [BsonRepresentation(BsonType.ObjectId)] Attributes that tell the MongoDB driver that this ID string should be interpreted as a collection ID and can be passed as a type string although Mongo wants internal 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, in which a class and an interface for the database settings are stored.

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.jsonby adding the following configuration:

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

You’ll have to create or rename that, of course Example Database, as well as create the Users Collection in it.

Finally, we’ll add some code Startup.cs by doing ConfigureServices Method that gets the settings from the appsettings.json File and register the interface through dependency injection:

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

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

    services.AddControllers();
}

You need to add a directive with your Models namespace above.

Writing a CRUD database service

Once the database is connected, you can add the service to do the talking. The following class contains a IMongoCollection This 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 over the database settings, starts a new client, gets the database and initializes the _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 series of CRUD operations for interacting with the database. Feel free to implement custom logic here.

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

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

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

    services.AddSingleton();

    services.AddControllers();
}

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

Set up an API controller

Next, you need a controller to perform API actions. Fortunately, Visual Studio makes this easy; You can right click on Controller to add a new controller with read / write actions. This will create a new controller with some basic methods.

Right click on

The route is defined above. By default, this is set to /api/controller, where controller is the name of the controller (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 populate that 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 schema you are saving. (You need to add a reference to your Models namespace, of course.) ActionResult is a dynamic type that either includes the TValue in it or an HTTP response result.

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

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

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

Then for the HttpPost method, call the Create method of your database service and return CreatedAtRoute, which sends a 201 response to the client informing it that the object creation 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 process the user input, do all the necessary checks and take the correct database actions, returning something useful or a status code to the user telling them what happened.

However, at this point you should be able to click the Run IIS Express button above and test the API. This will use the route as the weather service API by default that came with the boilerplate. Instead of typing them in each time, you can change the debug route under Project> Properties> Debug and change the Launch Browser option.

Change the debug route

Once you want to test on a remote server, you can create a production build via Build> Publish Service. Select the file output and edit the configuration according to your requirements. For example, you can choose to have a stand-alone build that packages all .NET dependencies with the build, and also publish it as a single executable file. You can also change the finish time here.

Production build settings

If you want to publish on Linux you need to add a runtime ID to your system .csproj File.

linux-x64

Of course, the API presented here is unsecured. ASP.NET has a great authentication system that has support for JWT-based tokens and can be configured to work with OAuth providers like Google and Facebook.


Source link