[go: up one dir, main page]

0% found this document useful (0 votes)
21 views39 pages

0. C#_ADO.Net_Notes_Final_Prints

The document provides an introduction to ASP.NET Web API, a framework for building HTTP services that can be consumed by various clients, including mobile devices and browsers. It outlines the features and advantages of using Web API over WCF and ASP.NET MVC, emphasizing its suitability for creating RESTful services and its lightweight architecture. Additionally, it explains the principles of REST and the structure of a REST API, including resources, request verbs, and response formats.

Uploaded by

omkarslawand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views39 pages

0. C#_ADO.Net_Notes_Final_Prints

The document provides an introduction to ASP.NET Web API, a framework for building HTTP services that can be consumed by various clients, including mobile devices and browsers. It outlines the features and advantages of using Web API over WCF and ASP.NET MVC, emphasizing its suitability for creating RESTful services and its lightweight architecture. Additionally, it explains the principles of REST and the structure of a REST API, including resources, request verbs, and response formats.

Uploaded by

omkarslawand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

MARCH 14, 2023

enosis
www.enosislearning.com

WEB API INTRODUCTION –NOTES

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

Introduction to Asp.Net Web API


Asp.Net Web API is a framework for building HTTP services that can be consumed by a broad range of
clients including browsers, mobiles, iphone and tablets.
It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action
results, filter, model binders, IOC container or dependency injection. But it is not a part of the MVC
Framework. It is a part of the core ASP.NET platform and can be used with MVC and other types of Web
applications like Asp.Net WebForms. It can also be used as a stand-alone Web services application.

Why Asp.Net Web API (Web API)?


Today, a web-based application is not enough to reach its customers. People are very smart, they are
using iphone, mobile, tablets etc. devices in its daily life. These devices also have a lot of apps for making
the life easy. Actually, we are moving from the web towards apps world.
So, if you like to expose your service data to the browsers and as well as all these modern devices apps
in fast and simple way, you should have an API which is compatible with browsers and all these devices.
For example twitter,facebook and Google API for the web application and phone apps.

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.

ASP.NET Web API features

1) ASP.NET Web API is much similar to ASP.NET MVC.


2) It contains similar features as ASP.NET MVC like:
Routing
Controllers
Action results

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.

Stand-alone services can be developed using the Web API.

5) ASP.NET Web API framework is widely used to develop RESTful services.

RESTful services

o Web API is the enhanced form of a web application.


o SOAP (Simple Object Access Protocol) was an XML based protocol
for developing the connected web applications.
o Problem with the SOAP was that with each request, Metadata is
attached with data to be transferred.
o This Metadata converts small data to heavy data on the server.
o Web API may or may not be RESTful services, but they are
always HTTP based services.
o REST stands for Representational State Transfer.
o In REST API, only the state of the object is sent to the server to find
the desired result.
o REST is an architectural pattern for developing an API that uses
HTTP as its underlying communication method.

When we are using HTTP based service, for example, BookMyShow app, we
need data in managed form like JSON format, XML format.

Client requests for the information by sending parameters using API


methods.

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."

It is a stateless, client-server model.

Page 33
WEB API INTRODUCTION –NOTES

Principles of REST API


The six principles of REST API are:

1. Stateless
2. Client-Server
3. Uniform Interface
4. Cacheable
5. Layered System
6. Code on demand

Why to choose Web API ?


1. If we need a Web Service and don’t need SOAP, then ASP.Net Web API is best choice.
2. It is Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.
3. It doesn't have tedious and extensive configuration like WCF REST service.
4. Simple service creation with Web API. With WCF REST Services, service creation is difficult.
5. It is only based on HTTP and easy to define, expose and consume in a REST-ful way.
6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
7. It is open source.

WCF or ASP.NET Web API


Below points can help you to choose WCF or ASP.NET Web API
 If you want to create resource based services and need to take full advantage of HTTP like cache control
for browsers, transfer different kind of content types like documents, images, HTML pages ASP.NET
Web API should be selected.
 If you have heterogeneous clients for same service and needs to call service using different protocols
like netTCPBinding, netNamedPipeBinding, wsHttpBinding WCF is the obvious choice.
 If you have special requirements like CallBackContract, One way communication or queuing
then WCF should be selected.

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

Asp.Net Web API VS Asp.Net MVC


1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API
is used to create full blown HTTP services with easy and simple way that returns only data not view.
2. Web API also takes care of returning data in particular format like JSON,XML or any other based upon
the Accept header in the request and you don't worry about that. MVC only return data in JSON format
using JsonResult.
3. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to
actions name.
4. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters,
routing and others MVC features exist in Web API are different from MVC and exists in the
new System.Web.Http assembly. In MVC, these features exist within System.Web.Mvc. Hence Web API
can also be used with Asp.Net and as a standalone service layer.
5. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which
may return data in JSON, XML or any others format and building a full blown HTTP service. Typically, this
will be called Web API self hosting.
6. When you have mixed MVC and Web API controller and you want to implement the authorization then
you have to create two filters one for MVC and another for Web API since boths are different.
7. Moreover, Web API is light weight architecture and except the web application it can also be used with
smart phone apps.

MVC WEB API


8. 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.

API; what and why?

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:

public IEnumerable<string> Get()


{
return new string[] { "value1", "value2" };
}

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:

public string Get(int id)


{
return "value";
}

There are many great hidden benefits to using Web API which you may not realise but actually save you
a lot of work.

Web API is part of ‘One ASP.net’


Web API is part of the ‘One ASP.net’ family which means that it natively supports all of the great shared
features you may currently use with MVC or web forms, this includes (these are just a few examples):

 Entity Framework
 Authorisation and identity
 Scaffolding
 Routing

Serialization and Model Binding


Web API is setup by default to provide responses in either XML or JSON (JSON is default). However, as a
developer you do not need to do any conversion or parsing – you simply return a strongly typed object
and Web API will convert it to XML or JSON and return it to the calling client, this is a process called
Content Negotiation. This is an example of a GET action which returns a strongly typed Product object.

public Product GetProduct(int id)


{
var product = _products.FirstOrDefault(p => p.ID == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);

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:

public HttpResponseMessage Post(Product product)


{
if (ModelState.IsValid)
{
// Do something with the product (not shown).

return new HttpResponseMessage(HttpStatusCode.OK);


}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}

Page 33
WEB API INTRODUCTION –NOTES

Differences between communication services

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

4. WEB API Services can be hosted on IIS or within the application


5. The Responses in Web API Services are formatted by MediaTypeFormatter into JSON,
XML or any custom format you want.

Dynamic API Help Pages


If you choose Web API as your project type, when you first create your project, you will get automated
documentation with your API. This is a regular MVC project that sits alongside your API. The help pages
project looks at your API code, models, attributes etc and constructs documentation automatically,
which includes examples, model definitions and more.

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.

Defining Attribute Routing in ASP.NET MVC

1. Controller level attribute routing


You can define routes at controller level which apply to all actions within the controller
unless a specific route is added to an action.

[RoutePrefix("MyHome")]

Page 33
WEB API INTRODUCTION –NOTES

[Route("{action=index}")] //default action

public class HomeController : Controller

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:

public class BooksController : ApiController


{
[Route("api/books")]
public IEnumerable<Book> GetBooks() { ... }

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) { ... }

// ...
}

The route prefix can include parameters:

[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.

The following table lists the constraints that are supported.

Constraint Description Example


Matches uppercase or lowercase Latin alphabet
alpha {x:alpha}
characters (a-z, A-Z)
bool Matches a Boolean value. {x:bool}
datetime Matches a DateTime value. {x:datetime}
decimal Matches a decimal value. {x:decimal}
double Matches a 64-bit floating-point value. {x:double}
float Matches a 32-bit floating-point value. {x:float}
guid Matches a GUID value. {x:guid}
int Matches a 32-bit integer value. {x:int}
Matches a string with the specified length or within a {x:length(6)}
length
specified range of lengths. {x:length(1,20)}
long Matches a 64-bit integer value. {x:long}
max Matches an integer with a maximum value. {x:max(10)}
maxlength Matches a string with a maximum length. {x:maxlength(10)}
min Matches an integer with a minimum value. {x:min(10)}
minlength Matches a string with a minimum length. {x:minlength(10)}
range Matches an integer within a range of values. {x:range(10,50)}
{x:regex(^\d{3}-\d{3}-\
regex Matches a regular expression.
d{4}$)}

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) { ... }

Custom Route Constraints

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.

public class NonZeroConstraint : IHttpRouteConstraint


{
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
object value;
if (values.TryGetValue(parameterName, out value) && value != null)
{
long longValue;
if (value is long)
{
longValue = (long)value;
return longValue != 0;
}

string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);


if (Int64.TryParse(valueString, NumberStyles.Integer,
CultureInfo.InvariantCulture, out longValue))
{
return longValue != 0;
}
}
return false;
}
}

The following code shows how to register the constraint:

public static class WebApiConfig


{
public static void Register(HttpConfiguration config)

Page 33
WEB API INTRODUCTION –NOTES

{
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));

config.MapHttpAttributeRoutes(constraintResolver);
}
}

Now you can apply the constraint in your routes:

[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.

Optional URI Parameters and Default Values

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.

public class BooksController : ApiController


{
[Route("api/books/locale/{lcid:int?}")]
public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... }
}

In this example, /api/books/locale/1033 and /api/books/locale return the same resource.

Alternatively, you can specify a default value inside the route template, as follows:

public class BooksController : ApiController


{
[Route("api/books/locale/{lcid:int=1033}")]
public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }
}

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.

public class BooksController : ApiController


{
[Route("api/books/{id}", Name="GetBookById")]
public BookDto GetBook(int id)
{
// Implementation not shown...
}

[Route("api/books")]
public HttpResponseMessage Post(Book book)
{
// Validate and add book to database (not shown)

var response = Request.CreateResponse(HttpStatusCode.Created);

// 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.

Here is how the total ordering is determined:

1. Compare the RouteOrder property of the route attribute.


2. Look at each URI segment in the route template. For each segment, order as follows:
1. Literal segments.
2. Route parameters with constraints.
3. Route parameters without constraints.
4. Wildcard parameter segments with constraints.
5. Wildcard parameter segments without constraints.
3. In the case of a tie, routes are ordered by a case-insensitive ordinal string comparison
(OrdinalIgnoreCase) of the route template.

Here is an example. Suppose you define the following controller:

[RoutePrefix("orders")]
public class OrdersController : ApiController
{
[Route("{id:int}")] // constrained parameter
public HttpResponseMessage Get(int id) { ... }

[Route("details")] // literal
public HttpResponseMessage GetDetails() { ... }

[Route("pending", RouteOrder = 1)]


public HttpResponseMessage GetPending() { ... }

[Route("{customerName}")] // unconstrained parameter


public HttpResponseMessage GetByCustomer(string customerName) { ... }

[Route("{*date:datetime}")] // wildcard
public HttpResponseMessage Get(DateTime date) { ... }
}

These routes are ordered as follows.

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

Then click on Next Tab and Name your application

Then click on Create Tab and then Select WEBAPI Template

Page 33
WEB API INTRODUCTION –NOTES

After selecting the template

Now,

Step 4:

Page 33
WEB API INTRODUCTION –NOTES

Add a class in Model Folder

Now create a class named as EMP and some fields

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; }
}

Now build your Project Once

Then Add Controller

Page 33
WEB API INTRODUCTION –NOTES

Now API Empty Controller is added

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

Now finally build once and run the Project

Output:

Page 33
WEB API INTRODUCTION –NOTES

Note: Output of WEBAPI is XML file.

Example 2

WEB Api with sql(crud)

Step 1

First, create a Blank Web API project as,

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:

Create Table Employees

( ID int,

FullName varchar(20),

LastName Varchar(20),

Gender Varchar(20),

Salary Int)

Page 33
WEB API INTRODUCTION –NOTES

Now Add ADO entity model

Page 33
WEB API INTRODUCTION –NOTES

Check your Connection string in web config file

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

After adding entity

Now, Add API controller

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);
}
}
}
}

Finally build the application and Run

Output:

Page 33
WEB API INTRODUCTION –NOTES

Page 33

You might also like