Web API
Web API is a platform for building
Restful Services.
Rest
- Representational state transfer
Rest is a simple way
of sending and receiving data between client and server and it doesn't have
very many standards defined. You can send and receive data as JSON, XML or even
plain text. Its light weighted compared to SOAP.
Web
API supports different formats of response data. Built-in support for JSON, XML
format.
Restful service is nothing but
design pattern.
Url based application developed by
Web APi only
Web api give the URl based on url
when hit the Url to get the response. That particular response access by PHP,
.NET, JAVA any other technology or any other application access by it.
Web api have a structure in the form
of mvc (Model View Controller).
In our web Api will not have any
concept of views, we have a model & controller, but views are nothing but url
what your going to get it.
In WEB API Controllers do not return
views, only part of Model and Controller.
WEB API Controller:
The
following is a simple controller class added by visual studio by default when
we created a new Web API project in the Create WEB API Project section.
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Net;
using
System.Net.Http;
using
System.Web.Http;
namespace
Asp.net_WebApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public
IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void
Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id,
[FromBody]string value)
{
}
// DELETE api/values/5
public void
Delete(int id)
{
}
}
}
As
you can see in the above example, ValuesController class is derived from
ApiController and includes multiple action methods whose names match with HTTP
verbs like Get, Post, Put and Delete
Whenever
you create web api methods by using prefix of HTTP verbs.
Difference between ApiController and Controller
- Web ApiController is Derives from System.Web.Http.ApiController class
Ex : public class ValuesController : ApiController
{
}
- MVC Controller is Derives from System.Web.Mvc.Controller class.
Ex: public class EmployeeController :
Controller
{
}
- Web Api Controller return data
- MVC Controller return View
- Web Api Controller Method name must start with Http verbs otherwise apply http verbs attribute.
- MVC Controller Must apply appropriate Http verbs attribute like HttpGet, HttpPost
How
to access web api controller in asp.net mvc project
Go through ur project (Asp.net
WebApi) -> App_Start -> WebApiConfig.cs file
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web.Http;
namespace
Asp.net_WebApi
{
public static class WebApiConfig
{
public static void
Register(HttpConfiguration config)
{
// Web API configuration and
services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id =
RouteParameter.Optional }
);
}
}
}
We can access through api/Controller
We can’t deal with action method
directly.
When u
build the web api application it shows like below:
The above
page comes from home control -> index.cshtml page it’s shows
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET
is a free web framework for building great Web sites and Web applications using
HTML, CSS, and JavaScript.</p>
<p><a href="https://asp.net" class="btn
btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting
started</h2>
<p>ASP.NET
Web API is a framework that makes it easy to build HTTP services that reach
a broad range of clients, including
browsers and mobile devices. ASP.NET Web API
is an ideal platform for building
RESTful applications on the .NET Framework.</p>
<p><a class="btn
btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301870">Learn
more »</a></p>
</div>
<div class="col-md-4">
<h2>Get
more libraries</h2>
<p>NuGet
is a free Visual Studio extension that makes it easy to add, remove, and update
libraries and tools in Visual Studio projects.</p>
<p><a class="btn
btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301871">Learn
more »</a></p>
</div>
<div class="col-md-4">
<h2>Web
Hosting</h2>
<p>You can
easily find a web hosting company that offers the right mix of features and
price for your applications.</p>
<p><a class="btn
btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301872">Learn
more »</a></p>
</div>
</div>
How to
get API link in above output screen
Go through
ur project like Asp.net WebApi ->
Areas -> Controllers -> HelpController.cs page
using
System;
using
System.Web.Http;
using
System.Web.Mvc;
using
Asp.net_WebApi.Areas.HelpPage.ModelDescriptions;
using
Asp.net_WebApi.Areas.HelpPage.Models;
namespace
Asp.net_WebApi.Areas.HelpPage.Controllers
{
/// <summary>
/// The
controller that will handle requests for the help page.
/// </summary>
public class HelpController :
Controller
{
private const string
ErrorViewName = "Error";
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
public HelpController(HttpConfiguration
config)
{
Configuration = config;
}
public
HttpConfiguration Configuration { get; private set; }
public
ActionResult Index()
{
ViewBag.DocumentationProvider =
Configuration.Services.GetDocumentationProvider();
return
View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public
ActionResult Api(string apiId)
{
if
(!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel =
Configuration.GetHelpPageApiModel(apiId);
if
(apiModel != null)
{
return
View(apiModel);
}
}
return
View(ErrorViewName);
}
public
ActionResult ResourceModel(string modelName)
{
if
(!String.IsNullOrEmpty(modelName))
{
ModelDescriptionGenerator
modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();
ModelDescription
modelDescription;
if
(modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out
modelDescription))
{
return
View(modelDescription);
}
}
return
View(ErrorViewName);
}
}
}
This
page will generate links for us like below
Note: Don't Change above code.
If changed method name in ValuesController.cs
page like below
// GET api/values
public
IEnumerable<string> AGet()
{
return new string[] { "value1", "value2" };
}
Now run the
application the output show like below
In above output screen Get and Post
Method are not visible in value
section, because we add A before GET
method. So, don’t write before GET method. The methods start with HTTP Verbs
only (Get, Post, Put, Delete).
If you want to change method name u
can add after Http Verbs like GetA.
// GET api/values
public
IEnumerable<string> GetA()
{
return new string[] { "value1", "value2" };
}
How many Get methods we can define in Web Api controller?
According to user requirement we can define no of get method in web api controller. The controller is a class so, in class we define no.of methods.
But, we can define same type of method without parameter in ValueController.cs page like below
// GET api/values
public
IEnumerable<string> GetA()
{
return new string[] { "value1", "value2" };
}
// GET api/values
public
IEnumerable<string> GetB()
{
return new string[] { "B1", "B2" };
}
In
above output Value section, we miss Get methods, if you want those method we can use route concept.
Web API Routing:
Web API routing is similar to ASP.NET Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.
Web API supports two types of routing:
1. Attribute Routing
2. Convention-based Routing
Attribute Routing:
Place on a controller or action to
expose it directly via a route.
When u have same
methods and same parameter in that time we use attribute base routing.
If you want to get through method you define Route like below
// GET api/values
public
IEnumerable<string> GetA()
{
return new string[] { "value1", "value2" };
}
// GET api/values
[Route("GetEmployee")]
public
IEnumerable<string> GetB()
{
return new string[] { "B1", "B2" };
}
When
you see two square bracket ([]) are there inside u write anything that is called as
attribute.
the above output it's add two more Get methods because u add
[Route("GetEmployee")]
that means we define two different method name and same Patten in that time we can use route method.
when u call GetEmployee (https://localhost:44387/GetEmployee) it will display output like below:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>B1</string>
<string>B2</string>
</ArrayOfstring>
I get B1 and B2 string
Now I define one more method in ValueController.cs page like below:
// GET api/values
public
IEnumerable<string> GetA()
{
return new string[] { "value1", "value2" };
}
[Route("GetEmployee")]
public
IEnumerable<string> GetB()
{
return new string[] { "B1", "B2" };
}
[Route("GetEmployeeInfo")]
public
IEnumerable<string> Getc()
{
return new string[] { "B1", "B2" };
}
when you build the application it's show like below
Incase if you want to define URL base, you define like below in your ValueController.cs page.
// GET api/values
public
IEnumerable<string> GetA()
{
return new string[] { "value1", "value2" };
}
[Route("api/Values/GetEmployee")]
public
IEnumerable<string> GetB()
{
return new string[] { "B1", "B2" };
}
[Route("api/Values/GetEmployeeInfo")]
public
IEnumerable<string> Getc()
{
return new string[] { "B1", "B2" };
}
when you build the application it's show like below
But any controller
(valueController.cs page) we can define no of method. if you create static url,
incase if you want to change the url we go each and every method then change. it's a time taking Processes that way RoutePrefix came into picture.
RoutePrefix:
A controller with a
route prefix that applies to all actions within the controller
It's
means before attribute routing
now we can change like below in ValueController.cs page.
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Net;
using
System.Net.Http;
using
System.Web.Http;
namespace
Asp.net_WebApi.Controllers
{
[RoutePrefix("api/Values")]
public class ValuesController :
ApiController
{
// GET api/values
public
IEnumerable<string> GetA()
{
return new string[] { "value1", "value2" };
}
[Route("GetEmployee")]
public
IEnumerable<string> GetB()
{
return new string[] { "B1", "B2" };
}
[Route("GetEmployeeInfo")]
public
IEnumerable<string> GetC()
{
return new string[] { "B1", "B2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void
Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id,
[FromBody]string value)
{
}
// DELETE api/values/5
public void
Delete(int id)
{
}
}
}
The output comes like below:
Convention-based Routing:
In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.
Now we define convention based routing in ValueController.cs page like below:
public IEnumerable<string> GetD(string name, string Designation)
{
return new string[] { "B1", "B2" };
}
when you run the application output show like below:
When u click the EmployeeInfoDetails it will show one window like
when you pass the parameters in convention-based routing it's display the querystring.
if we don't want to display querystring, then we go for attribute based routing.
No comments:
Post a Comment