How To Develop Web API in ASP.NET Core

To mention, developing Web API in ASP.NET Core is equivalent to decorating Web API in ASP.NET MVC with a few differences. The differences are mentioned below in brief:

  • Web API is not a separate framework. It got merged with ASP.NET Core MVC.
  • Previously a Web API class used to inherit from ApiController base class. Due to the merging mentioned above, the Web API doesn’t inherit from ApiController, in fact it inherits from the same Controller class that other controllers also inherit from.
  • As Web API is just another controller, you are free to have as many actions you want. Of course, to create a REST style service you still need to have those standard Get(), Post(), Put() and Delete() actions as before.
  • You can define the HTTP verb and action mapping at the action level using features like [HttpPost], [HttpPut] and [HttpDelete].

With the above overview, let’s build a simple REST style Web API that performs CRUD operations on the Customers table of the Northwind database.

Start by creating a new ASP.NET Core project using VS and pick the Web API project template.

The project contains ValuesController in the Controllers folder. Take note that the ValuesController inherits from Controller base class just like any other MVC controller.

Rename the default Web API class to CustomerServiceController. You will require database support for your service and hence you need to add NuGet packages for Entity Framework Core. You can do that through Project.json file:

….

“Microsoft.EntityFrameworkCore”: “1.0.1”,

“Microsoft.EntityFrameworkCore.SqlServer”: “1.0.1”

….

Take the Startup class and modify as shown below:

public class Startup

{

public void ConfigureServices

(IServiceCollection services)

{

services.AddMvc();

services.AddEntityFrameworkSqlServer();

}

public void Configure

(IApplicationBuilder app)

{

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}

/{action=Index}

/{id?}”);

});

}

}

The ConfigureServices() method sums up MVC and Entity Framework Core to the services collection. The Configure() method configures the MVC routing. This routing is not required by the Web API as such but is needed for local clients while consuming the Web API (as you will see in later parts).

Then add Models and Views folders to the project. Add Customer model class in the Models folder as given below:

[Table(“Customers”)]

public class Customer

{

[Key]

public string CustomerID { get; set; }

public string CompanyName { get; set; }

public string ContactName { get; set; }

public string Country { get; set; }

}

The Customer class is decorated with [Table] attribute that maps it to the Customers table. It contains four public properties namely CustomerID, CompanyName, ContactName and Country. The CustomerID is marked as the primary key using the [Key] attribute.

Then add NorthwindDbContext class to the Models folder and write the following code to it:

public class NorthwindDbContext:DbContext

{

public DbSet<Customer> Customers { get; set; }

protected override void OnConfiguring

(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer(“data source=.;

initial catalog=northwind;

integrated security=true”);

}

}

The NorthwindDbContext class acts as the DbContext for our data access and inherits from the DbContext class. The NorthwindDbContext defines Customers DbSet. The OnConfiguring() method configures the DbContext to use the SQL Server database with the specified connection string. Ensure to adjust the connection string to suit your need.

Now, open the CustomerServiceController and type the following code:

[Route(“api/[controller]”)]

public class CustomerServiceController : Controller

{

[HttpGet]

public List<Customer> Get()

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

return db.Customers.OrderBy(

i => i.CustomerID).ToList();

}

}

[HttpGet(“{id}”)]

public Customer Get(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

return db.Customers.Where(

i => i.CustomerID == id).SingleOrDefault();

}

}

[HttpPost]

public string Post([FromBody]Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Customers.Add(obj);

db.SaveChanges();

return “Customer added successfully!”;

}

}

[HttpPut(“{id}”)]

public string Put(string id, [FromBody] Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

return “Customer modified successfully!”;

}

}

[HttpDelete(“{id}”)]

public string Delete(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

var obj = db.Customers.Where(

i => i.CustomerID == id).SingleOrDefault();

db.Customers.Remove(obj);

db.SaveChanges();

return “Customer deleted successfully!”;

}

}

}

Take note of the following about the Web API you have created:

  • The CustomerServiceController is designed with [Route] feature that configures the routing for the Web API. The route adds /api is written after the name of the controller. So, our Web API will be located at /api/CustomerService.
  • The Web API comprise of five actions namely Get(), Get(id), Post(), Put(), Delete().
  • The HTTP verb to action mapping is done using the features – [HttpGet], [HttpPost], [HttpPut] and [HttpDelete] respectively.
  • The Customer parameter of the actions is model bound and makes use of the [FormBody] feature which indicates the parameter values that will be coming from the request’s body.
  • These features also specify the id route parameter when necessary.

Here in this article we shall not discuss the details of the Entity Framework Core code that is present in these actions. If you worked with EF before that code must be familiar to you. The above mentioned actions generally implement CRUD (create, read, update and delete) operations for the Customers table.

Ok. This completes the CustomerService Web API. Run the application and see the result. If all goes well you should see JSON customer objects removed in the browser.

Return of the IActionResult and HTTP status codes

In the above example the actions gave back the specific types like List<Customer>, Customer and string. However, that’s not required. You might return a generic IActionResult from all the Web API action methods. This technique gets easy when you want to indicate HTTP status codes along with the return values.

Consider the Put() method given below:

[HttpPut(“{id}”)]

public IActionResult Put(string id,

[FromBody] Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

return new ObjectResult

(“Customer modified successfully!”);

}

}

The Put() now returns IActionResult in place of a string. Inside, the code develops a new ObjectResult object to return a string value back to the caller. The ObjectResult sets the HTTP status code to 200 (Ok) and then returns the specific value to the caller. All the actions of our CustomerService Web API can be modified to use this technique.

If you don’t want to return anything from an action (void) then you can use NoContentResult object instead of ObjectResult. The NoContentResult returns HTTP status 204 (no content).

You can also use certain inbuilt methods to indicate the HTTP status code. Some of them are mentioned below:

  • Ok() : Gives back HTTP status code of 200 (ok).
  • BadRequest() : Gives back HTTP status code of 400 (bad request).
  • NotFound() : Gives back HTTP status code of 404 (not found).

The following code shows Get(id) action modified to use NotFound() method.

[HttpGet(“{id}”)]

public IActionResult Get(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

var data= db.Customers.Where

(i => i.CustomerID == id).SingleOrDefault();

if(data==null)

{

return NotFound(“Invalid CustomerID!”);

}

return new ObjectResult(data);

}

}

As you can see, the code now checks whether data is null or not. If it is null it indicates that the CustomerID was not found in the database and hence NotFound() method is called with a custom error message.

We conclude the discussion here.

Keep coding!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>