Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Nov 9, 2015

Enable Cross-Origin Requests CORS in ASP.NET Web API

For enabling the CORS request in the ASP.NET Web API project, we have to download the cors package from the Nuget, i.e., Microsoft.AspNet.WebApi.Cors.

Open up the Nuget Package Manager console from the Visual Studio Tools Option —> Library Package Manager —> Package Manager Console.

nuget package
Type the following command to install Cors Package:

Install-Package Microsoft.AspNet.WebApi.Cors

The above CORS package installs, along with any dependencies, into the ASP.NET Web API WebService project. Now open the file App_Start/WebApiConfig.cs and add the following code to the WebApiConfig.Registermethod.

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


Next, add the [EnableCors] attribute to the Controller class, as follows:

Enable Cors Per Controller

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebAPI.Controllers
{
    [EnableCors(origins: "http://www.vamsi.com", headers: "*", methods: "*")]
    public class APIHomeController : ApiController
    {
       Public string Get(int id)
       {
           return "value";
       }
    }
}



If you set [EnableCors] attribute controller class, then it will apply action result methods.
For disabling the Cors, set the [DisableCors] attribute for the particular controller or action method.

Enable Cors Per Action


namespace WebAPI.Controllers
{
    public class APIHomeController : ApiController
    {
      [EnableCors]
      Public string Get(int id)
       {
           return "value";
       }
    } 
}

For Enable Cors for the Entire ASP.NET Web API Project


public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.vamsi.com", "*", "*");
        config.EnableCors(cors);
    }
}

Aug 5, 2015

Top 5 New Features in ASP.NET Web API 2

ASP.NET Web API 2 has been released with a number of new exciting features. In this web development post, I’ll try to discuss new features of it which can be considered the top 5.

1. Attribute Routing

Along with convention-based routing, Web API 2 now supports attribute routing as well.
In case of convention-based routing, we can define multiple route templates. When a request comes, it will be matched against already defined route templates, and forwarded to specific controller action according to matched template.
You can see the following default route template in routing table for Web API:
 
Config.Routes.MapHttpRoute(
name: “DefaultApi”,
routeTemplate: “api/{Controller}/{id}”,
defaults: new { id = RouteParameter.Optional }
);
 
This routing approach has benefits that all routing templates are defined at one common location but for certain URI patterns, it really becomes difficult to support (like nested routing on same controller).
With ASP.NET Web API 2, we can easily support above mentioned URI pattern and others as well. Following shows an example of a URI pattern with attribute routing.
 
URI Pattern –> books/1/authors
 
[Route(“books/{bookId}/authors”)]
public IEnumerable<Author> GetAuthorByBook(int bookId) { ….. }
 

2. CORS – Cross Origin Resource Sharing

Normally, browsers don’t allow making cross-domain calls due to same-origin policy and we know that. So, what exactly is CORS (Cross Origin Resource Sharing)?
CORS is a mechanism that allows a web page to make an AJAX call to a domain other than the domain which actually rendered that specific web page. CORS is compliant with W3C standards and now ASP.NET Web API has support for it in version 2.

3. OWIN (Open Web Interface for .NET) self hosting

ASP.NET Web API 2 comes with a new self hosting package i.e. Microsoft.AspNet.WebApi. OwinSelfHost.
  According to http://owin.org/
“OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.”
So, according to above description, OWIN is an ideal option for self hosting a web application in a process other than IIS process.
There are a number of OWIN implementations like Giacomo, Kayak, Firefly etc. available (some may be partial or outdated) but Katana is the recommended one for Microsoft servers and Web API frameworks.

4. IHttpActionResult

Along with the existing two approaches of creating response from controller action, ASP.NET Web API 2 now supports another way of doing the same. IHttpResponseMessage is basically an interface which acts as a factory for HttpResponseMessage. It’s very powerful because it extensify web api. Using this approach we can compose any specific type of response.

5. Web API OData

The Open Data Protocol (OData) is actually a web protocol for querying and updating data. ASP.NET Web API 2 has added support for $expand, $select, and $value options for OData. By using these options, we can control the representation that is returned from the server.
  • $expand: Normally, response doesn’t include related entities if we query an OData collection. By using $expand, we can get related entities inline in response.
  • $select: It’s used if we wanted to include subset of properites in response instead of all.
  • $value: It allows to return raw value of the property instead returning in OData format.

 

Top 10 ASP.NET Web API Interview Questions

What is ASP.NET Web API?

ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework.
Using ASP.NET Web API we can create non-SOAP based services like plain XML or JSON strings etc. with many other advantages including:
  • Create resource-oriented services using the full features of HTTP.
  • Exposing services to a variety of clients easily like browsers or mobile devices etc.

What are the advantages of using ASP.NET Web API?

Using ASP.NET Web API has a number of advantages, but core of the advantages are:
  • It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE etc for all CRUD operations.
  • Complete support for routing.
  • Response generated in JSON or XML format using MediaTypeFormatter.
  • It has the ability to be hosted in IIS as well as self-host outside of IIS.
  • Supports Model binding and Validation.
  • Support for OData.
  • and more....

What new features are introduced in ASP.NET Web API 2.0?

More new features introduced in ASP.NET Web API framework v2.0 are as follows:
  • Attribute Routing
  • External Authentication
  • CORS (Cross-Origin Resource Sharing)
  • OWIN (Open Web Interface for .NET) Self Hosting
  • IHttpActionResult
  • Web API OData
You can follow a good Web API new feature details on Top 5 New Features in ASP.NET Web API 2 here.

WCF Vs ASP.NET Web API?

Actually, Windows Communication Foundation is designed to exchange standard SOAP-based messages using variety of transport protocols like HTTP, TCP, NamedPipes or MSMQ etc.
On the other hand, ASP.NET API is a framework for building non-SOAP based services over HTTP only.
For more details, please follow here.

Is it true that ASP.NET Web API has replaced WCF?

It's a misconception that ASP.NET Web API has replaced WCF. It's another way of building non-SOAP based services, for example, plain XML or JSON string etc.
Yes, it has some added advantages like utilizing full features of HTTP and reaching more clients such as mobile devices etc.
But WCF is still a good choice for following scenarios:
  • If we intended to use transport other than HTTP e.g. TCP, UDP or Named Pipes.
  • Messag Queuing scenario using MSMQ.
  • One-way communication or Duplex communication
A good understanding for WCF(Windows Communication Foundation), please follow WCF Tutorial.

MVC Vs ASP.NET Web API?

As in previous ASP.NET Web API Interview Questions, we discussed that purpose of Web API framework is to generate HTTP services that reaches more clients by generating data in raw format, for example, plain XML or JSON string. So, ASP.NET Web API creates simple HTTP services that renders raw data.
On the other hand, ASP.NET MVC framework is used to develop web applications that generates Views as well as data. ASP.NET MVC facilitates in rendering HTML easy.
MVC Vs Web API
For ASP.NET MVC Interview Questions, follow the link.

How to return View from ASP.NET Web API method?

(A tricky Interview Question) No, we can't return view from ASP.NET Web API Method. As we discussed in earlier interview question about difference between ASP.NET MVC and Web API that ASP.NET Web API creates HTTP services that renders raw data. Although, it's quite possible in ASP.NET MVC application.

How to restrict access to Web API method to specific HTTP Verb?

Attribute programming plays it's role here. We can easily restrict access to an ASP.NET Web API method to be called using a specific HTTP method. For example, we may required in a scenario to restrict access to a Web API method through HTTP POST only as follows:
 [HttpPost]
 public void UpdateStudent(Student aStudent)
 {
       StudentRepository.AddStudent(aStudent); 
 }

Can we use Web API with ASP.NET Web Form?

Yes, ASP.NET Web API is bundled with ASP.NET MVC framework but still it can be used with ASP.NET Web Form.
It can be done in three simple steps as follows:
  1. Create a Web API Controller.
  2. Add a routing table to Application_Start method of Global.asax.
  3. Make a jQuery AJAX Call to Web API method and get data.

How we can provide an alias name for ASP.NET Web API action?

We can provide an alias name for ASP.NET Web API action same as in case of ASP.NET MVC by using "ActionName" attribute as follows:
 [HttpPost]
[ActionName("SaveStudentInfo")]
 public void UpdateStudent(Student aStudent)
 {
       StudentRepository.AddStudent(aStudent); 
 }

Sep 11, 2013

what is Web API in MVC and how differ from WCF?

ASP.NET Web API is one of new exciting feature of ASP.NET MVC 4. It is ideal framework for creating RESTful applications with .NET framework. It makes easy to build HTTP services and reach large number of clients like browsers and mobile devices. You can use XML or JSON or something else with these API.
ASP.NET Web API allows you create api or http based service or client endpoints. Although it comes with ASP.NET MVC4, it is much flexible framework to develop REST and AJAX API for HTML5, ASP.NET Web forms, client server desktop applications. Unlike WCF Web API does not required much configuration settings and you can host it in your own applications.

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.