Nandu Singh

Nandu Singh

1572418211

How to make Web API with ASP.NET Core 3.0 and MongoDB

This tutorial creates a web API that performs Create, Read, Update, and Delete (CRUD) operations on a MongoDB NoSQL database.

In this tutorial, you learn how to:

  • Configure MongoDB
  • Create a MongoDB database
  • Define a MongoDB collection and schema
  • Perform MongoDB CRUD operations from a web API
  • Customize JSON serialization

Create database with MongoDB

How to Install MongoDB 4.x on MacOS with Homebrew

Open another command shell instance. Connect to the default test database by running the following command:

mongo

Run the following in a command shell:

use BookstoreDb

If it doesn’t already exist, a database named BookstoreDb is created. If the database does exist, its connection is opened for transactions.

Create a Books collection using following command:

db.createCollection('Books')

The following result is displayed:

{ "ok" : 1 }

Define a schema for the Books collection and insert two documents using the following command:

db.Books.insertMany([{'Name':'Design Patterns','Price':54.93,'Category':'Computers','Author':'Ralph Johnson'}, {'Name':'Clean Code','Price':43.15,'Category':'Computers','Author':'Robert C. Martin'}])

The following result is displayed:

{
  "acknowledged" : true,
  "insertedIds" : [
    ObjectId("5bfd996f7b8e48dc15ff215d"),
    ObjectId("5bfd996f7b8e48dc15ff215e")
  ]
}

View the documents in the database using the following command:

db.Books.find({}).pretty()

The following result is displayed:

{
  "_id" : ObjectId("5bfd996f7b8e48dc15ff215d"),
  "Name" : "Design Patterns",
  "Price" : 54.93,
  "Category" : "Computers",
  "Author" : "Ralph Johnson"
}
{
  "_id" : ObjectId("5bfd996f7b8e48dc15ff215e"),
  "Name" : "Clean Code",
  "Price" : 43.15,
  "Category" : "Computers",
  "Author" : "Robert C. Martin"
}

The database is ready. You can start creating the ASP.NET Core web API.

Create the ASP.NET Core web API project

  1. Go to File > New > Project.

  2. Select the ASP.NET Core Web Application project type, and select Next.

  3. Name the project BooksApi, and select Create.

  4. Select the .NET Core target framework and ASP.NET Core 3.0. Select the API project template, and select Create.

  5. Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. In the Package Manager Console window, navigate to the project root. Run the following command to install the .NET driver for MongoDB:

Install-Package MongoDB.Driver -Version {VERSION}

Add an entity model

  1. Add a Models directory to the project root.
  2. Add a Book class to the Models directory with the following code:
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace BooksApi.Models
{
    public class Book
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("Name")]
        public string BookName { get; set; }

        public decimal Price { get; set; }

        public string Category { get; set; }

        public string Author { get; set; }
    }
}

In the preceding class, the Id property:

  • Is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
  • Is annotated with [BsonId] to designate this property as the document’s primary key.
  • Is annotated with [BsonRepresentation(BsonType.ObjectId)] to allow passing the parameter as type string instead of an ObjectId structure. Mongo handles the conversion from string to ObjectId.
  • The BookName property is annotated with the [BsonElement] attribute. The attribute’s value of Name represents the property name in the MongoDB collection.

Add a configuration model

Add the following database configuration values to appsettings.json:

{
  "BookstoreDatabaseSettings": {
    "BooksCollectionName": "Books",
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "BookstoreDb"
  },
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}

Add a BookstoreDatabaseSettings.cs file to the Models directory with the following code:

namespace BooksApi.Models
{
    public class BookstoreDatabaseSettings : IBookstoreDatabaseSettings
    {
        public string BooksCollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }

    public interface IBookstoreDatabaseSettings
    {
        string BooksCollectionName { get; set; }
        string ConnectionString { get; set; }
        string DatabaseName { get; set; }
    }
}

The preceding BookstoreDatabaseSettings class is used to store the appsettings.json file’s BookstoreDatabaseSettings property values. The JSON and C# property names are named identically to ease the mapping process.

Add the following highlighted code to Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    // requires using Microsoft.Extensions.Options
    services.Configure<BookstoreDatabaseSettings>(
        Configuration.GetSection(nameof(BookstoreDatabaseSettings)));

    services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
        sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);

    services.AddControllers();
}

In the preceding code:

The configuration instance to which the appsettings.json file’s BookstoreDatabaseSettings section binds is registered in the Dependency Injection (DI) container. For example, a BookstoreDatabaseSettings object’s ConnectionString property is populated with the BookstoreDatabaseSettings:ConnectionString property in appsettings.json.

The IBookstoreDatabaseSettings interface is registered in DI with a singleton service lifetime. When injected, the interface instance resolves to a BookstoreDatabaseSettings object.

Add the following code to the top of Startup.cs to resolve the BookstoreDatabaseSettings and IBookstoreDatabaseSettings references:

using BooksApi.Models;

Add a CRUD operations service

Add a Services directory to the project root.

Add a BookService class to the Services directory with the following code:

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

namespace BooksApi.Services
{
    public class BookService
    {
        private readonly IMongoCollection<Book> _books;

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

            _books = database.GetCollection<Book>(settings.BooksCollectionName);
        }

        public List<Book> Get() =>
            _books.Find(book => true).ToList();

        public Book Get(string id) =>
            _books.Find<Book>(book => book.Id == id).FirstOrDefault();

        public Book Create(Book book)
        {
            _books.InsertOne(book);
            return book;
        }

        public void Update(string id, Book bookIn) =>
            _books.ReplaceOne(book => book.Id == id, bookIn);

        public void Remove(Book bookIn) =>
            _books.DeleteOne(book => book.Id == bookIn.Id);

        public void Remove(string id) => 
            _books.DeleteOne(book => book.Id == id);
    }
}

In the preceding code, an IBookstoreDatabaseSettings instance is retrieved from DI via constructor injection. This technique provides access to the appsettings.json configuration values that were added in the Add a configuration model section.

Add the following highlighted code to Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<BookstoreDatabaseSettings>(
        Configuration.GetSection(nameof(BookstoreDatabaseSettings)));

    services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
        sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);

    services.AddSingleton<BookService>();

    services.AddControllers();
}

In the preceding code, the BookService class is registered with DI to support constructor injection in consuming classes. The singleton service lifetime is most appropriate because BookService takes a direct dependency on MongoClient. Per the official Mongo Client reuse guidelines, MongoClient should be registered in DI with a singleton service lifetime.

Add the following code to the top of Startup.cs to resolve the BookService reference:

using BooksApi.Services;

The BookService class uses the following MongoDB.Driver members to perform CRUD operations against the database:

MongoClient – Reads the server instance for performing database operations. The constructor of this class is provided the MongoDB connection string:

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

    _books = database.GetCollection<Book>(settings.BooksCollectionName);
}

IMongoDatabase – Represents the Mongo database for performing operations. This tutorial uses the generic GetCollection(collection) method on the interface to gain access to data in a specific collection. Perform CRUD operations against the collection after this method is called. In the GetCollection<TDocument>(collection) method call:

collection represents the collection name.
TDocument represents the CLR object type stored in the collection.

GetCollection<TDocument>(collection) returns a MongoCollection object representing the collection. In this tutorial, the following methods are invoked on the collection:

DeleteOne – Deletes a single document matching the provided search criteria.
Find<TDocument> – Returns all documents in the collection matching the provided search criteria.
InsertOne – Inserts the provided object as a new document in the collection.
ReplaceOne – Replaces the single document matching the provided search criteria with the provided object.

Add a controller

Add a BooksController class to the Controllers directory with the following code:

using BooksApi.Models;
using BooksApi.Services;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace BooksApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private readonly BookService _bookService;

        public BooksController(BookService bookService)
        {
            _bookService = bookService;
        }

        [HttpGet]
        public ActionResult<List<Book>> Get() =>
            _bookService.Get();

        [HttpGet("{id:length(24)}", Name = "GetBook")]
        public ActionResult<Book> Get(string id)
        {
            var book = _bookService.Get(id);

            if (book == null)
            {
                return NotFound();
            }

            return book;
        }

        [HttpPost]
        public ActionResult<Book> Create(Book book)
        {
            _bookService.Create(book);

            return CreatedAtRoute("GetBook", new { id = book.Id.ToString() }, book);
        }

        [HttpPut("{id:length(24)}")]
        public IActionResult Update(string id, Book bookIn)
        {
            var book = _bookService.Get(id);

            if (book == null)
            {
                return NotFound();
            }

            _bookService.Update(id, bookIn);

            return NoContent();
        }

        [HttpDelete("{id:length(24)}")]
        public IActionResult Delete(string id)
        {
            var book = _bookService.Get(id);

            if (book == null)
            {
                return NotFound();
            }

            _bookService.Remove(book.Id);

            return NoContent();
        }
    }
}

The preceding web API controller:

  • Uses the BookService class to perform CRUD operations.
  • Contains action methods to support GET, POST, PUT, and DELETE HTTP requests.
  • Calls CreatedAtRoute in the Create action method to return an HTTP 201 response. Status code 201 is the standard response for an HTTP POST method that creates a new resource on the server. CreatedAtRoute also adds a Location header to the response. The Location header specifies the URI of the newly created book.

Test the web API

  1. Build and run the app.
  2. Navigate to http://localhost:<port>/api/books to test the controller’s parameterless Get action method. The following JSON response is displayed:
[
  {
    "id":"5bfd996f7b8e48dc15ff215d",
    "bookName":"Design Patterns",
    "price":54.93,
    "category":"Computers",
    "author":"Ralph Johnson"
  },
  {
    "id":"5bfd996f7b8e48dc15ff215e",
    "bookName":"Clean Code",
    "price":43.15,
    "category":"Computers",
    "author":"Robert C. Martin"
  }
]

Navigate to http://localhost:<port>/api/books/{id here} to test the controller’s overloaded Get action method. The following JSON response is displayed:

{
  "id":"{ID}",
  "bookName":"Clean Code",
  "price":43.15,
  "category":"Computers",
  "author":"Robert C. Martin"
}

Configure JSON serialization options

There are two details to change about the JSON responses returned in the Test the web API section:

The property names’ default camel casing should be changed to match the Pascal casing of the CLR object’s property names.
The bookName property should be returned as Name.
To satisfy the preceding requirements, make the following changes:

JSON.NET has been removed from ASP.NET shared framework. Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson.

In Startup.ConfigureServices, chain the following highlighted code on to the AddMvc method call:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<BookstoreDatabaseSettings>(
        Configuration.GetSection(nameof(BookstoreDatabaseSettings)));

    services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
        sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);

    services.AddSingleton<BookService>();

    services.AddControllers()
        .AddNewtonsoftJson(options => options.UseMemberCasing());
}

With the preceding change, property names in the web API’s serialized JSON response match their corresponding property names in the CLR object type. For example, the Book class’s Author property serializes as Author.

In Models/Book.cs, annotate the BookName property with the following [JsonProperty] attribute:

[BsonElement("Name")]
[JsonProperty("Name")]
public string BookName { get; set; }

The [JsonProperty] attribute’s value of Name represents the property name in the web API’s serialized JSON response.

Add the following code to the top of Models/Book.cs to resolve the [JsonProperty] attribute reference:

using Newtonsoft.Json;

Repeat the steps defined in the Test the web API section. Notice the difference in JSON property names.

Source Code

View and download source code

#aspnet #mongodb #aspnet-core #webapi

What is GEEK

Buddha Community

How to make Web API with ASP.NET Core 3.0 and MongoDB
Einar  Hintz

Einar Hintz

1602560783

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.

Sub-topics discussed :

  • Form design for insert and update operation.
  • Display forms in modal popup dialog.
  • Form post using jQuery Ajax.
  • Implement MVC CRUD operations with jQuery Ajax.
  • Loading spinner in .NET Core MVC.
  • Prevent direct access to MVC action method.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).

From new project window, Select Asp.Net Core Web Application_._

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Setup a Database

Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define DB model class file – /Models/TransactionModel.cs.

public class TransactionModel
{
    [Key]
    public int TransactionId { get; set; }

    [Column(TypeName ="nvarchar(12)")]
    [DisplayName("Account Number")]
    [Required(ErrorMessage ="This Field is required.")]
    [MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
    public string AccountNumber { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Beneficiary Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BeneficiaryName { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Bank Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BankName { get; set; }

    [Column(TypeName ="nvarchar(11)")]
    [DisplayName("SWIFT Code")]
    [Required(ErrorMessage = "This Field is required.")]
    [MaxLength(11)]
    public string SWIFTCode { get; set; }

    [DisplayName("Amount")]
    [Required(ErrorMessage = "This Field is required.")]
    public int Amount { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }
}

C#Copy

Here we’ve defined model properties for the transaction with proper validation. Now let’s define  DbContextclass for EF Core.

#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup

Einar  Hintz

Einar Hintz

1602564619

MVC User Registration & Login with ASP.NET Core Identity

User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.

Sub-topics discussed :

  • How to add ASP.NET Core Identity to MVC application.
  • Customize ASP.NET Core Identity.
  • Identity.UI Design Customization.
  • Next step.

Background

ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.

ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.

Showing how to create an MVC application with ASP.NET Core Identity API

The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.

Create an ASP.NET Core MVC Project

First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.

Create an ASP.NET Core Web application

Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.

Select Model View Controller templet under .NET Core

#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core

Authorization in asp.net core

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework

AllowAnonymous in asp.net core

#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework

Einar  Hintz

Einar Hintz

1602564706

Running WordPress on ASP.NET Core with Peachpie

In this article, you will learn how to use or integrate WordPress in ASP.NET and Running WordPress on ASP.NET Core, without PHP, or any source files on the server. The following demonstration will show you how to add WordPress as a frontend to an existing ASP.NET Core application step by step.

Running WordPress on NET Core

WordPress is a free, simplest, and most popular open-source content management system to create your own website or blog which is written in PHP and paired up with MySQL. WordPress on .Net Core is possible with peachpie, which is a compiler built on top of the Roslyn platform, it’s a set of runtime and base class libraries and everything that allows compiling a PHP project, a group of PHP files into a regular .net project.

Peachpie allows for seamless both-way interoperability between PHP and .NET applications. In simpler terms, this means that one can have some parts of an application written in PHP, while other modules are written in .NET and everything will work together as one application. Here is the original Repository of the WordPress SDK by PeachPie.

Here are the following steps to run WordPress with ASP.Net Core:-

Step1: Open your Visual Studio IDE and Create a new project – > ASP.NET Core Web Application

create new project | wordpress on asp.net core

Step 2: Select Web Application: A project template for creating an ASP.Net Core application with example ASP.Net Razor Pages Content.

#.net core #asp.net #wordpress asp.net core #wordpress on asp.net core #wordpress with asp.net core