0. C#_ADO.Net_Notes_Final_Prints
0. C#_ADO.Net_Notes_Final_Prints
enosis
www.enosislearning.com
Enosis Learning
WEB API INTRODUCTION –NOTES
Page 33
WEB API INTRODUCTION –NOTES
Contents
Introduction to Asp.Net Web API................................................................................................................2
Why Asp.Net Web API (Web API)?..........................................................................................................2
Web API Features....................................................................................................................................2
Why to choose Web API ?.......................................................................................................................3
WCF or ASP.NET Web API........................................................................................................................3
Asp.Net Web API VS Asp.Net MVC..........................................................................................................3
MVC WEB API.............................................................................................................................................4
API; what and why?.....................................................................................................................................4
What is REST?..........................................................................................................................................6
What is .net Web API?.............................................................................................................................7
Web API is part of ‘One ASP.net’.........................................................................................................8
Serialization and Model Binding..........................................................................................................8
Differences between communication services..........................................................................................10
Web Service:......................................................................................................................................10
WCF:.....................................................................................................................................................10
WCF Rest:...........................................................................................................................................10
Dynamic API Help Pages....................................................................................................................11
In Summary...........................................................................................................................................11
Defining Attribute Routing in ASP.NET MVC..............................................................................................11
1. Controller level attribute routing...............................................................................................11
HTTP Methods.......................................................................................................................................12
Route Prefixes.......................................................................................................................................12
Route Constraints.................................................................................................................................14
Custom Route Constraints................................................................................................................15
Optional URI Parameters and Default Values......................................................................................16
Route Names.........................................................................................................................................17
Route Order..........................................................................................................................................18
Page 33
WEB API INTRODUCTION –NOTES
Web API is the great framework for exposing your data and service to different-different devices.
Moreover Web API is open source an ideal platform for building REST-ful services over the .NET
Framework. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response
headers) and you don't need to define any extra config settings for different devices unlike WCF Rest
service.
Page 33
WEB API INTRODUCTION –NOTES
Filter
Model, etc.
3) There is a misconception that ASP.NET Web API is a part of ASP.NET MVC
framework, while it can be used with any other type of web application.
RESTful services
When we are using HTTP based service, for example, BookMyShow app, we
need data in managed form like JSON format, XML format.
Page 33
WEB API INTRODUCTION –NOTES
For example, if we want to book a show for which we want to know the
details like City, Movie Name, Place, Timing. We will send the state of the
object to the web-server, and API will check whether the data is available or
not.
If the data is available (the movie is available for that instance), then it will
send back the response to the client with the object.
Values of an object are sent to the client, i.e., basically state of an object is
sent to the client, so each time you don't have to create an object.
Note: "REST API is an architectural style as well as an approach for communications purpose that is
often used in various web developments."
Page 33
WEB API INTRODUCTION –NOTES
1. Stateless
2. Client-Server
3. Uniform Interface
4. Cacheable
5. Layered System
6. Code on demand
Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only
data not view.
Web API helps to build REST-ful services over the .NET Framework and it also support content-
negotiation(it's about deciding the best response format data that could be acceptable by the client. it
could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.
Page 33
WEB API INTRODUCTION –NOTES
Let’s start right at the start and figure out what an API is and why you should consider using one.
The term API stands for ‘Application Programming Interface’. In the world of web development the term
‘API’ is synonymous with online web services which client apps can use to retrieve and update data.
Page 33
WEB API INTRODUCTION –NOTES
These online services have had several names/formats over the years such as SOAP, however the
current popular choice is to create a REST (or Restful) API.
We’ll come onto REST and why REST is now preferred later, but first let’s examine why you would even
bother with an API.
Let’s consider a modern application which may include several mobile apps on various platforms and
usually some kind of web application too. Without an API, a basic architecture may look like this where
each client app has its own embedded business logic.
Notice that each client app has its own embedded business logic (probably written in several different
languages) which connects directly to the database to get, update and manipulate data. This local
business logic means that the client apps can easily become complex and all need to be maintained in
sync with each other. When a new feature is required, you’ll have to update each app accordingly. This
can be a very expensive process which often leads to feature fragmentation, bugs and can really hold
back innovation.
Now let’s consider the same architecture with a central API which hold all the business logic.
Page 33
WEB API INTRODUCTION –NOTES
Each app uses the same API to get, update and manipulate data. All apps have feature parity and when
you need to make a change you just make it in one place in line with the ‘Don’t Repeat Yourself’ (DRY)
principle of software development. The apps themselves then become relatively lightweight UI layers.
What is REST?
REST stands for ‘Representational State Transfer’ and it is an architectural pattern for creating an API
that uses HTTP as its underlying communication method. REST was originally conceived by Roy Fielding
in his 2000 dissertation paper entitled ‘Architectural Styles and the Design of Network-based Software
Almost every device that is connected to the internet already uses HTTP; it is the base protocol that the
internet is built on which is why it makes such a great platform for an API.
HTTP is a request and response system; a calling client sends a request to an endpoint and the endpoint
responds. The client and endpoint can be anything but a typical example is a browser accessing a web
server or an app accessing and API.
There are several key implementation details with HTTP that you should be aware of:
Resources – REST uses addressable resources to define the structure of the API. These are the
URLs you use to get to pages on the web, for example ‘http://www.microsoft.com/Surface-Pro-
3’ is a resource
Request Verbs – These describe what you want to do with the resource. A browser typically
issues a GET verb to instruct the endpoint it wants to get data, however there are many other
verbs available including things like POST, PUT and DELETE. See the full list
athttp://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
Request Headers – These are additional instructions that are sent with the request. These might
define what type of response is required or authorisation details. See the full list
athttp://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Request Body - Data that is sent with the request. For example a POST (creation of a new item)
will required some data which is typically sent as the request body in the format of JSON or XML.
Page 33
WEB API INTRODUCTION –NOTES
Response Body – This is the main body of the response. If the request was to a web server, this
might be a full HTML page, if it was to an API, this might be a JSON or XML document.
Response Status codes – These codes are issues with the response and give the client details on
the status of the request. See the full list at www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
In the context of a REST API, resources typically represent your data entities (i.e. ‘Product’, ‘Person’,
‘Order’ etc). The verb that is sent with the request informs the API what to do with the resource, for
example a GET request gets data about an entity, POST requests create a new entity.
There is a convention in place that GET requests to an entity url such as /Products returns a list of
products, possibly matching some criteria that was sent with the request. However, to retrieve a specific
product, you would use the product’s ID as part of the resource, for example /Products/81 would return
product with the ID of 81. It is also possible to use query string parameters with an API, for example you
may have something like /Products?Colour=red which returns all red products.
These are some typical requests you might expect to see in an ecommerce API:
Response
Resource Verb Expected Outcome
Code
/Products GET A list of all products in the system 200/OK
A list of all products in the system
/Products?Colour=red GET 200/OK
where the colour is red
/Products POST Creation of a new product 201/Created
/Products/81 GET Product with ID of 81 200/OK
/Products/881(a product ID which 404/Not
GET Some error message
does not exist) Found
An update to the product with an ID of 204/No
/Products/81 PUT
81 Content
Deletion of the product with an ID of 204/No
/Products/81 DELETE
81 Content
/Customers GET A list of all customers 200/OK
What is .net Web API?
.Net’s Web API is an easy way to implement a RESTful web service using all of the goodness that the .net
framework provides. Once you understand the basic principles of REST, then a .net Web API will be very
easy to implement.
Web API is built on .net’s modular, pluggable pipeline model. This means that when a server hosting a
web API receives a request, it passes through .nets request pipeline first. This enables you to easily add
your own modules if you find that the default capabilities are not enough for your needs. With the
recent announcements on ASP.net vNext this also means you can potentially host your Web API outside
of Windows Server which opens up a whole range of usage cases. See http://www.asp.net/vnext for
detail.
Web API uses the Controller and Action concepts from MVC so if you already understand .net MVC you
are in a good place. If you don’t, then Web API is a great way to learn MVC.
Page 33
WEB API INTRODUCTION –NOTES
Resources are mapped directly to controllers; you would typically have a different controller for each of
your main data entities (Product, Person, Order etc). Web API uses the .net routing engine to map URLs
to controllers. Typically, APIs are held within a ‘/api/’ route which helps to distinguish API controllers
from other non-API in the same website.
Actions are used to map to specific HTTP verbs, for example you would typically have a GET action which
returns all of the entities. This action would respond to /api/Products (where ‘products’ is your
controller) and would look something like this:
You may also have a GET action which accepts a specific ID and returns a specific entity. It would
respond to /api/Products/81 and would look something like this:
There are many great hidden benefits to using Web API which you may not realise but actually save you
a lot of work.
Entity Framework
Authorisation and identity
Scaffolding
Routing
Page 33
WEB API INTRODUCTION –NOTES
}
return Request.CreateResponse(HttpStatusCode.OK, product);
}
This also works for incoming requests using a feature called Model Validation. With Model Validation,
Web API is able to validate and parse incoming response body data to a strongly typed object for you to
work with in your code. This is an example of model binding:
Page 33
WEB API INTRODUCTION –NOTES
The .NET framework has a number of technologies that allow us to create HTTP
services such as Web Service, WCF, WCF Rest and now WEB API. Following are the
differences between these four:
Web Service:
1. The Web Service is based on SOAP and it returns the data in XML format.
2. It supports only the HTTP protocol.
3. Web Service is not an open source but it can be consumed by any client who
understands XML.
4. It can only be hosted on IIS.
WCF:
1. WCF is also based on SOAP and it also returns the data in the form of XML.
2. Unlike Web service, WCF supports different types of protocols (transport protocol) such
as TCP, Named Pipes, HTTP, HTTPS, and MSMQ.
3. The main problem with WCF service it required lots of configuration which is a headache
for a developer.
4. Like Web Service, WCF is also not open source but it can be consumed by any client
who understands XML.
5. WCF can be host within in the application or on IIS or using window service.
WCF Rest:
1. To use a WCF service as WCF Rest service we have to enable webHttpBindings.
2. WCF Rest supports the HTTP verbs such as GET and POST by using the [WebGet] and
[WebInvoke] attributes respectively.
3. To use other HTTP verbs you have to do some configuration in the IIS so that it will
accept the request of that particular verb on .svc file
4. It supports different data formats such as XML, JSON, and Atom format.
WEB API:
1. The Web API Framework is a new framework that is basically used for developing HTTP
based services in easy and simple way.
2. Unlike WCF Rest Service, it uses the full HTTP features such as URIs, request/response
headers, caching, versioning, and various data formats.
3. The ASP.NET Web API also supports most of the MVC features such as routing,
controllers, actions, filter, model binders, IOC container, dependency injection, unit
testing which makes it more simple and robust.
Page 33
WEB API INTRODUCTION –NOTES
This documentation makes for a great resource to help developers of calling client understand the
structure of your API. Help pages are contained within a route called ‘/help/’.
In Summary
To summarise, use of an API will make the architecture of your application much cleaner, making it
easier to add features and fix bugs as your project progresses.
REST is an architectural pattern which is based on HTTP and uses HTTP requests, responses, verbs and
status codes to communicate. The fact that REST services use HTTP means they can be consumed by
almost any ‘online’ device or application (including IoT devices such as toasters, cars, pedometers etc) –
no proprietary knowledge of the API is required.
Web API in .net is the way you write REST APIs services in .net. Web API gives you all the benefits of
the .net framework and deals with a lot of the complexities of content negotiation, model binding etc
that you’d have to deal with yourself without Web API.
ASP.NET MVC5 and WEB API 2 supports a new type of routing, called attribute routing. In this routing,
attributes are used to define routes. Attribute routing provides you more control over the URIs by
defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.
[RoutePrefix("MyHome")]
Page 33
WEB API INTRODUCTION –NOTES
HTTP Methods
Web API also selects actions based on the HTTP method of the request (GET, POST, etc).
By default, Web API looks for a case-insensitive match with the start of the controller method
name. For example, a controller method named PutCustomers matches an HTTP PUT request.
You can override this convention by decorating the mathod with any the following attributes:
[HttpDelete]
[HttpGet]
[HttpHead]
[HttpOptions]
[HttpPatch]
[HttpPost]
[HttpPut]
The following example maps the CreateBook method to HTTP POST requests.
[Route("api/books")]
[HttpPost]
public HttpResponseMessage CreateBook(Book book) { ... }
For all other HTTP methods, including non-standard methods, use the AcceptVerbs attribute,
which takes a list of HTTP methods.
// WebDAV method
[Route("api/books")]
[AcceptVerbs("MKCOL")]
public void MakeCollection() { }
Route Prefixes
Often, the routes in a controller all start with the same prefix. For example:
Page 33
WEB API INTRODUCTION –NOTES
[Route("api/books/{id:int}")]
public Book GetBook(int id) { ... }
[Route("api/books")]
[HttpPost]
public HttpResponseMessage CreateBook(Book book) { ... }
}
You can set a common prefix for an entire controller by using the [RoutePrefix] attribute:
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET api/books
[Route("")]
public IEnumerable<Book> Get() { ... }
// GET api/books/5
[Route("{id:int}")]
public Book Get(int id) { ... }
// POST api/books
[Route("")]
public HttpResponseMessage Post(Book book) { ... }
}
Use a tilde (~) on the method attribute to override the route prefix:
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET /api/authors/1/books
[Route("~/api/authors/{authorId:int}/books")]
public IEnumerable<Book> GetByAuthor(int authorId) { ... }
// ...
}
[RoutePrefix("customers/{customerId}")]
public class OrdersController : ApiController
{
Page 33
WEB API INTRODUCTION –NOTES
// GET customers/1/orders
[Route("orders")]
public IEnumerable<Order> Get(int customerId) { ... }
}
Route Constraints
Route constraints let you restrict how the parameters in the route template are matched. The
general syntax is "{parameter:constraint}". For example:
[Route("users/{id:int}"]
public User GetUserById(int id) { ... }
[Route("users/{name}"]
public User GetUserByName(string name) { ... }
Here, the first route will only be selected if the "id" segment of the URI is an integer. Otherwise,
the second route will be chosen.
Page 33
WEB API INTRODUCTION –NOTES
Notice that some of the constraints, such as "min", take arguments in parentheses. You can
apply multiple constraints to a parameter, separated by a colon.
[Route("users/{id:int:min(1)}")]
public User GetUserById(int id) { ... }
You can create custom route constraints by implementing the IHttpRouteConstraint interface.
For example, the following constraint restricts a parameter to a non-zero integer value.
Page 33
WEB API INTRODUCTION –NOTES
{
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
config.MapHttpAttributeRoutes(constraintResolver);
}
}
[Route("{id:nonzero}")]
public HttpResponseMessage GetNonZero(int id) { ... }
You can also replace the entire DefaultInlineConstraintResolver class by implementing the
IInlineConstraintResolver interface. Doing so will replace all of the built-in constraints, unless
your implementation of IInlineConstraintResolver specifically adds them.
You can make a URI parameter optional by adding a question mark to the route parameter. If a
route parameter is optional, you must define a default value for the method parameter.
Alternatively, you can specify a default value inside the route template, as follows:
This is almost the same as the previous example, but there is a slight difference of behavior
when the default value is applied.
Page 33
WEB API INTRODUCTION –NOTES
In the first example ("{lcid?}"), the default value of 1033 is assigned directly to the
method parameter, so the parameter will have this exact value.
In the second example ("{lcid=1033}"), the default value of "1033" goes through the
model-binding process. The default model-binder will convert "1033" to the numeric
value 1033. However, you could plug in a custom model binder, which might do
something different.
(In most cases, unless you have custom model binders in your pipeline, the two forms will be
equivalent.)
Route Names
In Web API, every route has a name. Route names are useful for generating links, so that you
can include a link in an HTTP response.
To specify the route name, set the Name property on the attribute. The following example
shows how to set the route name, and also how to use the route name when generating a link.
[Route("api/books")]
public HttpResponseMessage Post(Book book)
{
// Validate and add book to database (not shown)
// Generate a link to the new book and set the Location header in the response.
string uri = Url.Link("GetBookById", new { id = book.BookId });
response.Headers.Location = new Uri(uri);
return response;
}
}
Route Order
Page 33
WEB API INTRODUCTION –NOTES
When the framework tries to match a URI with a route, it evaluates the routes in a particular
order. To specify the order, set the RouteOrder property on the route attribute. Lower values
are evaluated first. The default order value is zero.
[RoutePrefix("orders")]
public class OrdersController : ApiController
{
[Route("{id:int}")] // constrained parameter
public HttpResponseMessage Get(int id) { ... }
[Route("details")] // literal
public HttpResponseMessage GetDetails() { ... }
[Route("{*date:datetime}")] // wildcard
public HttpResponseMessage Get(DateTime date) { ... }
}
1. orders/details
2. orders/{id}
3. orders/{customerName}
4. orders/{*date}
Page 33
WEB API INTRODUCTION –NOTES
5. orders/pending
Notice that "details" is a literal segment and appears before "{id}", but "pending" appears last
because the RouteOrder property is 1. (This example assumes there are no customers named
"details" or "pending". In general, try to avoid ambiguous routes. In this example, a better route
template for GetByCustomer is "customers/{customerName}" )
Example of WEB-API
Step1
Open Visual Studio (I am using Visual studio 2022) and from the File menu, select New and
then click on the Project. It will open a New Project window.
Step2:
Select a template
Page 33
WEB API INTRODUCTION –NOTES
Page 33
WEB API INTRODUCTION –NOTES
Now,
Step 4:
Page 33
WEB API INTRODUCTION –NOTES
Class Code:
Page 33
WEB API INTRODUCTION –NOTES
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace EnosisDemoWEBAPI.Models
{
public class Emp
{
public int EmpID { get; set; }
public string EmpName { get; set; }
public string Dept { get; set; }
public int Salary { get; set; }
}
Page 33
WEB API INTRODUCTION –NOTES
Controller Code:
using EnosisDemoWEBAPI.Models;
using System;
using System.Collections.Generic;
Page 33
WEB API INTRODUCTION –NOTES
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace EnosisDemoWEBAPI.Controllers
{
public class EmpController : ApiController
{
Emp[] emps = new Emp[]
{
new Emp { EmpID = 1, EmpName = "Pritam G", Dept= "Finance", Salary = 120000 },
new Emp { EmpID = 2, EmpName = "Pooja T", Dept= "HR", Salary = 160000 },
new Emp { EmpID = 3, EmpName = "Piyush B", Dept= "IT", Salary = 190000 },
};
public IEnumerable<Emp> GetEmps()
{
return emps;
}
In Controller we have created a list on the class Emp same as in mvc Controller
Output:
Page 33
WEB API INTRODUCTION –NOTES
Example 2
Step 1
File->New->Project.
Page 33
WEB API INTRODUCTION –NOTES
Then
Now, in SQL Server, I have a table called Employee Data which has 5 fields as Id, FirstName,
LastName, Gender, and Salary.
Page 33
WEB API INTRODUCTION –NOTES
Scirpt:
( ID int,
FullName varchar(20),
LastName Varchar(20),
Gender Varchar(20),
Salary Int)
Page 33
WEB API INTRODUCTION –NOTES
Page 33
WEB API INTRODUCTION –NOTES
Page 33
WEB API INTRODUCTION –NOTES
Now, the question is - "Where is this Employee Data that has come from this Employee.?". In
our SQL server, our table name is employeeData. So, right click on that and go to definition,
You will see the following.
The next step is to create an instance of our DBContext class. So, we have EmployeeDatamodel.edmx file
in which we have EmployeeDataModel.Context.cs file, and we have TESTEntities which inherits from
DbContext class.
Page 33
WEB API INTRODUCTION –NOTES
Page 33
WEB API INTRODUCTION –NOTES
Code:
Page 33
WEB API INTRODUCTION –NOTES
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEBAPIwithSQL2.Models;
namespace WEBAPIwithSQL2.Controllers
{
public class EmpController : ApiController
{
public IEnumerable<Employee> Get()
{
using (WEBAPI_DBEntities1 dbContext = new WEBAPI_DBEntities1())
{
return dbContext.Employees.ToList();
}
}
public Employee Get(int id)
{
using (WEBAPI_DBEntities1 dbContext = new WEBAPI_DBEntities1())
{
return dbContext.Employees.FirstOrDefault(e => e.ID == id);
}
}
}
}
Output:
Page 33
WEB API INTRODUCTION –NOTES
Page 33