HI WELCOME TO SIRIS
Showing posts with label web api. Show all posts
Showing posts with label web api. Show all posts

Comparing Asp.Net Web API Routing and Asp.Net MVC Routing

As you know, Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. A URL pattern is matched against the routes patterns defined in the Route dictionary in an Order and the first match wins. This means the first route which successfully matches a controller, action, and action parameters defined in the URL will call into the specified controller and action.
Asp.Net MVC application and Asp.Net Web API must have at least one route defined in order to function. Hence, Visual Studio templates defined for MVC and Web API must have a default route. Now let's understand the difference between Asp.Net MVC and Asp.Net Web API.

Default Route Pattern

The default route pattern for a Web API Project is defined as follows-
  1. config.Routes.MapHttpRoute(
  2. name: "DefaultApi", //route name
  3. routeTemplate: "api/{controller}/{id}", //route pattern
  4. defaults: new { id = RouteParameter.Optional } //parameter default values
  5. );
The literal api at the beginning of the Web API route pattern, makes it distinct from the standard MVC route. This is not mandatory but it is a good convention to differ Web API route from MVC route.
In Web API route pattern {action} parameter is optional but you can include an {action} parameter. Also, the action methods defined on the controller must be have an HTTP action verb as a prefix to the method name in order to work. So, you can also define the route for Web API as follows-
  1. config.Routes.MapHttpRoute(
  2. name: "DefaultApi",//route name
  3. routeTemplate: "api/{controller}/{action}/{id}",//route pattern
  4. defaults: new { id = RouteParameter.Optional }//parameter default values
  5. );
The default route pattern for an Asp.Net MVC Project is defined as follows-
  1. routes.MapRoute(
  2. name: "Default", //route name
  3. url: "{controller}/{action}/{id}", //route pattern
  4. defaults: new
  5. {
  6. controller = "Home",
  7. action = "Index",
  8. id = UrlParameter.Optional
  9. } //parameter default values
  10. );
As you have seen there is no literal before at the beginning of the Asp.Net MVC route pattern but you can add if you wish.

Route Processing

In Web API route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the API controller must either have the HTTP action verbs (GET, POST, PUT, DELETE) or have one of the HTTP action verbs as a prefix for the Actions methods name as given below-
  1. public class ValuesController : ApiController
  2. {
  3. // GET api/
  4. public IEnumerable Get()
  5. {
  6. return new string[] { "value1", "value2" };
  7. }
  8. // GET api//5
  9. public string Get(int id)
  10. {
  11. return "value";
  12. }
  13. // POST api/
  14. public void Post([FromBody]string value)
  15. {
  16. }
  17. // PUT api//5
  18. public void Put(int id, [FromBody]string value)
  19. {
  20. }
  21. // DELETE api//5
  22. public void Delete(int id)
  23. {
  24. }
  25. }
  26. // OR You can also defined above API Controller as Verb Prefix
  27. public class ValuesController : ApiController
  28. {
  29. // GET api/values
  30. public IEnumerable GetValues()
  31. {
  32. return new string[] { "value1", "value2" };
  33. }
  34. // GET api/values/5
  35. public string GetValues(int id)
  36. {
  37. return "value";
  38. }
  39. // POST api/values
  40. public void PostValues([FromBody]string value)
  41. {
  42. }
  43. // PUT api/values/5
  44. public void PutValues(int id, [FromBody]string value)
  45. {
  46. }
  47. // DELETE api/values/5
  48. public void DeleteValues(int id)
  49. {
  50. }
  51. }
In Asp.Net MVC route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the MVC controller do not have HTTP action verbs as a prefix for the Actions methods but they have name like as normal method as shown below-
  1. public class HomeController : Controller
  2. {
  3. // GET: /Home/Index
  4. public ActionResult Index() //method - Index
  5. {
  6. // To Do:
  7. return View();
  8. }
  9.  
  10. // Post: /Home/Index
  11. [HttpPost]
  12. public ActionResult Index(LoginModel model, string id)
  13. {
  14. // To Do:
  15. return View();
  16. }
  17. }
In MVC, by default HTTP verb is GET for using others HTTP verbs you need defined as an attribute but in Web API you need to define as an method's name prefix.

Complex Parameter Processing

Unlike MVC, URLs in Web API cannot contain complex types. Complex types must be placed in the HTTP message body and there should be only one complex type in the body of an HTTP message.

Base Library

Web API controllers inherit from System.Web.Http.Controller, but MVC controllers inherit from System.Web.Mvc.Controller. Both the library are different but acts in similar fashion.
What do you think?
I hope you will enjoy the tips while programming with Asp.Net MVC and Web API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Difference between WCF and Web API and WCF REST and Web Service

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles on the internet which may describe to whom you should use. Nowadays, you have a lot of choices to build HTTP services on .NET framework.
In this article, I would like to share my opinion with you over Web Service, WCF and now Web API. For more information about Web API refers What is Web API and why to use it ?.

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  1. To use WCF as WCF Rest service you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To Whom Choose Between WCF or WEB API

  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.
What do you think?
I hope, you have got when to use WCF, Web API and Web Service. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Difference between SOAP And REST APIs

I am sure everyone of us has sign-up in an online shopping website at least once. Let me consider Myntra or Paytm. When you visit the site, you come across three ways of signing up, either you can use your Facebook or Google credentials or can simply fill up a registration form for the same. When you select Google and you are only asked for your google credentials and your Myntra account is created in fraction of seconds. Isn’t that great!! But the question here is, does Myntra has access to Google’s database? OBVIOUSLY NOT!! Myntra has simply integrated Google API within their website.
Now what is this API in front of Google? When you click on Google to sign-up, Myntra takes your credentials and forwards them to Google and Google sends the user data like user Name, Image, Email Id as a response which is utilized by Myntra to create the account. In short, there is some sort of data exchange between two domains, Myntra and Google. So, the one who is responsible to process the request-response communication is known as API – Application Programming Interface. APIs are few lines of code which takes the request from the requester and gives back the response in form of data. Few of you must be thinking how can I integrate google in my website? The link for more detailshttps://developers.google.com/identity/sign-in/web/sign-in.

Web Service

If we think of Google functionalities which can be integrated in our application, we have Google Maps, Google Search, Gmail and many more. The link for more details https://developers.google.com/apis-explorer/#p/.
So, when you click on Google button, in the above example, along with your credentials, a keyword denoting which service Myntra is willing to access is sent to Google. Google in turn reads the keyword and hits the desired HTTP request to call the Sign-in API viz the Gmail API. This kind of communication which involves HTTP or Network is known as a Web Service. Similarly, websites like Shein.com, Zomato also uses Google Gmail API for user registration/sign up irrespective of the platform the websites are written in, viz. Java, .Net, PHP.

Are API And Web Services Similar?

An obvious question which popped-up in your mind is, So Web Service and API are same, right? My answer is, IT’S NOT. All web services are API but not all APIs are web service. Confused?? Let me explain.
As I mentioned earlier APIs are few lines of code which takes the request from the requester and gives back the response in form of data. Now suppose you are creating a utility class where you have written certain methods and can be reused in other different classes. In this case also we are exchanging data but not making use of any HTTP protocols or networks. Hence, I can term my utility class as an API but not as a Web Service. The most popular Web Service Protocols are
  1. SOAP – Simple Object Access Protocol
  2. REST – Representational State Transfer
Let’s start understanding them one by one.

SOAP based Web Seervice

Recently I mentioned that web services can be called by any application irrespective of the platform being used to write the code. Now imagine a scenario where this wouldn’t have been possible. So, for every platform, there must be a web service and for every web service managing different code, HTTP or network would result in difficult maintenance.
To enable different application to use the same web service, there has to be an intermediate language – XML (Extensible Markup Language). Almost every coding platform understands XML. But the drawback is XML don’t have any fixed specification across the programming languages. Hence to avoid such scenario, SOAP protocol was introduced.SOAP is an XML-Based protocol to work over HTTP which has few fixed specifications to be used across all programming languages.SOAP specification is known as SOAP Message. Following are the building blocks in a SOAP Message,


SOAP Envelope : Recognizes where the XML is a SOAP. This element is mandatory.


SOAP Header : Contains header information. For e.g. we need to pass username and password as a mandatory parameter in the request. We can define the same along with the datatypes under ComplexType tag. See below. This element is optional.


SOAP Body : Contains the webservice URL and the elements to be passed with the request, i.e. ComplexType values.


To understand in more detail over SOAP request and Response, you can go through the below link http://www.soapuser.com/basics3.html

REST based Web Service

SOAP requires a good amount of bandwidth to exchange data. Due to the complex structure, a small group of developers came up with REST, an architectural based web services, i.e. defined HTTP methods by which two applications can exchange data along with different formats like JSON, XML, Text to exchange data and response code to identify the response status. JSON is the most popular format.Following four HTTP methods are commonly used in REST based architecture.
  • GET – to fetch data from the application
  • POST – if you want to send new data to the application for processing
  • DELETE – if you wish to remove an existing data
  • PUT – if you wish to update any existing data


    A REST implementation basically contains the below elements,
  • URL – This contains the webservice URL.
  • HTTP Method – Describes what kind of request is the URL all about
  • Header – this element is used to tell the format in which the response is expected
  • Request Body – contains the requested web service details. It also contains the data you want to send to the other application.
  • Response Body – contains the data requested
  • Response Status code

Difference Between SOAP And REST

SOAP
REST
Slower due to defined specification
Faster as there is no defined specifications
Request and response format is always XML
Request and Response can be either in XM, JSON or plain text.
Requires bandwidth as the amount of data to transfer is a lot
Can work perfect even in case of low bandwidth
It is a protocol that defines some specifications which are to be followed strictly
Due to its architectural approach, it doesn’t have any strict specification
Less preferred due to its complex design
Easy to implement
Highly secure as it has its own security.
Doesn’t have its own security. Hence depends on application defined security
HTTP SSL Encryption and WS-Security encryption are used to secure SOAP messages
Data can be secured only by HTTP SSL Encryption
No need of caching mechanism
Requires caching mechanism
Can communicate over HTTP as well as SMTP
Can communicate only over HTTP

Chossing Between SOAP and REST

Use SOAP for,
  • if your application requires high level of security
  • Both consumer and provider should agree to the specification format
    Use REST for,
    • If each operation, i.e. Create, Read, Update, and Delete are independent of each other
    • If you need to cache any information
    • The bandwidth is limited
    Summary
    Selecting between SOAP and REST depends completely on the actual application requirements as there are many factors involved. Depending on them, one needs to check the benefits and decide upon the API. But as a heads up, I would like to conclude everything in a simple way. According to me, the applications, where exchanging data should be highly secure, for e.g. transaction security or processing data with BPEL, I would suggest using SOAP. On the other hand, applications which require fast responses, for e.g. social media, its advisable to use REST.

Difference between ASP.NET MVC and ASP.NET Web API

While developing your web application using MVC, many developers got confused when to use Web API, since MVC framework can also return JSON data by using JsonResult and can also handle simple AJAX requests. In previous article, I have explained the Difference between WCF and Web API and WCF REST and Web Service and when to use Web API over others services. In this article, you will learn when to use Web API with MVC.

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 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.
  3. 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.
  4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
  5. 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 featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.
  6. 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.
  7. 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.
  8. Moreover, Web API is light weight architecture and except the web application it can also be used with smart phone apps.
What do you think?
I hope you have got when to use Web API over MVC and how it works. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

What is Web API and why to use it?

Today, a web-based application is not enough to reach it's 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, caching, versioning, various content formats) and you don't need to define any extra config settings for different devices unlike WCF Rest service.

Web API Features

  1. Supports convention-based CRUD actions, since it works with HTTP verbs GET,POST,PUT and DELETE.
  2. Responses have an Accept header and HTTP status code.
  3. Supports multiple text formats like XML, JSON etc. or you can use your custom MediaTypeFormatter.
  4. May accepts and generates the content which may not be object oriented like images, PDF files etc.
  5. Automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  6. Supports Self-hosting or IIS Hosting.
  7. Supports the ASP.NET MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection.

Web API Version History

The following versions of ASP.NET Web API are released:

Web API 1.0

  • .NET Framework 4.0
  • ASP.NET MVC 4
  • VS 2010

Web API 2.0

  • .NET Framework 4.5
  • ASP.NET MVC 5
  • VS 2012, 2013

Why to choose Web API?

  1. If you need a Web Service and don’t need SOAP, then ASP.NET Web API is best choice.
  2. Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.
  3. Easy configuration unlike WCF REST service.
  4. Simple service creation with Web API. With WCF REST Services, service creation is difficult.
  5. Based on HTTP and so easy to define, expose and consume in a REST-ful way.
  6. Based on light weight RESTful architecture and good for devices which have limited bandwidth like smart phones.
  7. Open Source.
What do you think?
I hope you have enjoyed the article and would able to have a clear picture about Web API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

How to get base URL in Web API controller?

In the action method of the request to the url "http://localhost:85458/api/ctrl/"
var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;
this will get you http://localhost:85458

Asp Net Web API 2.1 get client IP address

string clientAddress = HttpContext.Current.Request.UserHostAddress;