DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • ASP.NET Web API: Benefits and Why to Choose It
  • Alexa Skill With .NET Core
  • CRUD Operations Using ASP.NET Web API, MongoDB, and Angular 8
  • Login and Registration ASP.NET Web API Using Angular 8

Trending

  • Building an Effective Zero Trust Security Strategy for End-To-End Cyber Risk Management
  • Operational Excellence Best Practices
  • The Art of Manual Regression Testing
  • A Complete Guide To Implementing GraphQL for Java
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Backend Web API With C#: Step-by-Step Tutorial

Backend Web API With C#: Step-by-Step Tutorial

Lean how to create a .NET-based backend application in VS that pulls from a Web API using the C# language.

By 
Andrey Prikaznov user avatar
Andrey Prikaznov
·
Aug. 27, 18 · Tutorial
Like (18)
Save
Tweet
Share
466.3K Views

Join the DZone community and get the full member experience.

Join For Free

The question of choosing a language for server backend logic is one of the most important questions for almost every developer, especially for a beginner. At the moment there are a lot of different languages : Java, .NET (C#, VD), Ruby, Python, Perl, JavaScript (Node.js), Go, C++.

Besides the syntactic features of these languages, there are also many other problems/questions to consider, such as the possibility of expansion, the use of different types of databases, a high learning curve, the requirements for fault tolerance, huge amounts of data, and so on.

Which languages are the most popular? Which one should you use? Whatever the pros and cons of each language may be, the fact remains the two most used languages today are Java and .NET.

This tutorial explains how you can build your own web server (Web API) using C# (ASP.NET). It is important to note that to host your server you will need to have Windows-based hosting.

Prerequisites

First of all, as we are working with C#, you need to use Microsoft Visual Studio (you can get it at the official Microsoft website).

Also, you will need to enable IIS (Internet Information Services):

  • Open Control Panel in Windows 10, click Programs, then find the "Programs and Features" section and click "Turn Windows features on or off".

  • Here, find the Internet Information Services. Click the + icon in front of it to expand all the available options under it. You can find the FTP Server, Web Management Tools, and World Wide Web Services. Now enable the Web Management Tools. Click OK and the selected feature (or features) will be added and applied to your Windows.

Step 1: Create a New Project

Open Microsoft Visual Studio and create a new project (File -> New -> Project). Select the "Installed" Templates, select Visual C#, then select Web. In the list of available templates, select ASP.NET Web Application (.NET Framework). Give your project a name (for my demo, I put "webapi"), then click OK.

In the next modal dialog, you may choose any suitable template. Let's select Web API, so it will prepare all the basic, initial files for the project. Click OK.

Done. Now you can browse the generated folders and files in the Solution Explorer. There are application configs, help page data, a few controllers, fonts, and CSS and JS files.

Routing Table

By default, the server uses the Routing Table located in App_Start/WebApiConfig.cs.

Image title

Pay attention to routeTemplate: "api/{controller}/{id}", it explains the API routing.

Now, let's make a basic example. In this tutorial, we will prepare an API for users, which is a pretty general entity/object of every system.

Adding a User Model

The model represents the user, thus we will include various fields like id, name, email, phone, and role.

In Solution Explorer, right-click in the Models folder, select Add, then select Class. Then provide a class name: User. The model class is ready.

Now we just add all the fields we decided to add:

public class User
{
    public int id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string phone { get; set; }
    public int role { get; set; }
}

Add a User Controller

In the Web API, the controller is an object that handles all HTTP requests. In Solution Explorer, right-click the Controllers. Select Add, then select Controller.

In the given dialog, select the Web API 2 Controller with read/write actions. Name the controller, UsersController. It will prepare the controller with all the proper CRUD actions.

I prepared a basic example with a dummy list of users:

public class UsersController : ApiController
{
    private User[] users = new User[]
    {
        new User { id = 1, name = "Haleemah Redfern", email = "email1@mail.com", phone = "01111111", role = 1},
        new User { id = 2, name = "Aya Bostock", email = "email2@mail.com", phone = "01111111", role = 1},
        new User { id = 3, name = "Sohail Perez", email = "email3@mail.com", phone = "01111111", role = 1},
        new User { id = 4, name = "Merryn Peck", email = "email4@mail.com", phone = "01111111", role = 2},
        new User { id = 5, name = "Cairon Reynolds", email = "email5@mail.com", phone = "01111111", role = 3}
    };
    // GET: api/Users
    [ResponseType(typeof(IEnumerable<User>))]
    public IEnumerable<User> Get()
    {
        return users;
    }
    // GET: api/Users/5
    public IHttpActionResult Get(int id)
    {
        var product = users.FirstOrDefault((p) => p.id == id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
    ...

Step 2: Deployment

Now you can build your solution (Ctrl+Shift+B in Visual Studio). Once the build has succeeded, you can run it. Click F5 and it will open in your browser automatically at your localhost in an available port (e.g. http://localhost:61024/). Most likely, you don't want to keep it constantly running in Visual Studio, so it'd be better to keep it as service.

In this case, we can deploy it to a local dedicated server using IIS (Internet Information Services).

First, open the IIS, on the left side under Sites - add a New Website (from the right panel or right-click on the Sites). Put in the following details: Site name, "webapi.localhost.net"; Physical path, "C:\projects\webapi" (where your solution is located); Binding - http or https; the host name will be the same, i.e. "webapi.localhost.net." Click OK.

IIS should run the Web API service on webapi.localhost.net.

If you try to open webapi.localhost.net in your browser, it won't open the result we created, because the browser tries to resolve this address (webapi.localhost.net) as a global domain. In order to map this domain name with the local server, we need to modify the local hosts file. On Windows (v10) the hosts file exists in the C:\Windows\system32\drivers\etc folder. The file doesn't have its own extension, it is the "host's" file.

Copy it to another location and open it in the editor.

You need to add the following to the end of this file:

# Web API host
127.0.0.1       webapi.localhost.net

Now you need to put the modified file back in the C:\Windows\system32\drivers\etc folder. As this folder is protected by Windows by default, you will get an access denied warning message, so you need to copy the file "As Administrator."

After the file is updated, webapi.localhost.net should load from your localhost (C:\projects\webapi).

Testing the API

It is time to test the API methods we created for our Web server: api/users and api/users/{id}. Open http://webapi.localhost.net/api/users in your browser. You should get the following output:

As we are creating the external API which should be accessible from outside our IDE, we need to test our API from another page. The easiest way is to do so is via the development toolbar (which exists in any modern browser). Usually it is activated when you press F12. Go to the 'Console' tab. Below I prepared two small examples you can use to test the APIs

In case jQuery is available, you can use:

$.ajax({
    type: "GET",
    url: 'http://webapi.localhost.net/api/users',
    success: (data) => {
        console.log(data);
    }
});

Otherwise, using native JavaScript, you can use the following code:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://webapi.localhost.net/api/users');
xhr.onload = function() {
    console.log(xhr.response);
};
xhr.send();

Very likely you will receive the following error:

The response to the preflight request doesn't pass an access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource, because regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.

Adjust Cross-Origin Resource Sharing (CORS)

In order to solve this, we need to enable the CORS in our solution. In Visual Studio, open the Package Manage Console (available at the bottom of your screen, between Error List and Output). Run the following: Install-Package Microsoft.AspNet.WebApi.Cors

This will install the WebApi.Cors reference. Then open the "App_Start\WebApiConfig.cs" file. Add

config.EnableCors();

before

config.MapHttpAttributeRoutes();

Then go back to our UsersController.cs and add [EnableCors(origins: "*", headers: "*", methods: "*")] before the class definition.

Finally - rebuild the project again. Then try to test the APIs again; now it should work.

I hope you enjoyed this article and you found it useful.

API Web Service csharp Web API Microsoft Visual Studio

Published at DZone with permission of Andrey Prikaznov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • ASP.NET Web API: Benefits and Why to Choose It
  • Alexa Skill With .NET Core
  • CRUD Operations Using ASP.NET Web API, MongoDB, and Angular 8
  • Login and Registration ASP.NET Web API Using Angular 8

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: