Calling Web API Service from ASP.Net MVC Controller Action | ASP.Net MVC Tutorial | ASP.Net MVC Programmer Guide

Calling a Web API Service from an ASP.Net MVC Controller is very simple. We can achieve this scenario with the help of the object HttpClient,

Below C# code snippet gives you a good example on calling a Web API Service from an ASP.Net MVC Controller

  1. using System;   
  2.  using System.Collections.Generic;   
  3.  using System.Linq;   
  4.  using System.Text;   
  5.  using System.Threading.Tasks;   
  6.  using System.Net.Http;   
  7.  using System.Runtime.Serialization.Json;   
  8.  using Newtonsoft.Json;   
  9.    
  10.  namespace FRPI.WebApi.Helper   
  11.  {       
  12.      public class DeserializeData   
  13.      {   
  14.          readonly string webUrl = "http://IpaddressOrDomainName/RootFolder/api/Controller/";   
  15.          public List<OrderDetails> GetInvoiveNo(string invoiceno) {   
  16.              string uri = webUrl + invoiceno;   
  17.              using (HttpClient httpClient = new HttpClient()) {   
  18.                  Task<String> response = httpClient.GetStringAsync(uri);   
  19.                  return JsonConvert.DeserializeObjectAsync<List<OrderDetails>>(response.Result).Result;   
  20.              }   
  21.          }   
  22.      }   
  23.  }  

Brief about HTTP Transaction? | ASP.Net Web API Interview Question | ASP.Net Web API Programmer Guide

,

HTTP is an application layer protocol based on a reliable transport layer protocol (read TCP). The two endpoints of the communication based on HTTP are a server and a client. The client sends a request to the server; the server processes the request and sends a response back to the client that includes a status code denoting if the processing is successful or not. These steps constitute an HTTP transaction. The client typically is a web browser such as Internet Explorer, and the server is a web server such as IIS. A web server services multiple clients simultaneously. The HTTP client initiates an HTTP request by connecting to a port (typically 80) on the web server.
Web servers host resources that are uniquely identified through an identifier called the Uniform Resource Identifier (URI). The Uniform Resource Locator (URL) is a URI—it identifies a resource but it also specifies how a representation of a resource can be obtained. For example, http://www.server.com/home.html is a URL that includes three parts.
  1.  Scheme, which is http://. The scheme denotes the protocol used (HTTP).
  2. Server, which is www.server.com. The server is the server that hosts the resource.
  3. Resource path, which is /home.html. The resource path is the path of the resource on the server.


A client requests the server to take an action on a resource. There is a noun and a verb associated with the request. The noun is the resource identified by the URI. The verb is the action or the HTTP method. In the above figure, the client requests GET on /home.html. The server responds with a 200 OK status code and sends the text/html representation of the resource. The server specifies the representation (text/html) in the Content-Type response header. The content type is also called the media type.

Including Limited Properties using BindAttribute in ASP.Net MVC | Avoiding Over-Posting Data using Bind Attribute | ASP.Net MVC Programmer Guide

Bind attribute (BindAttribute) represents an attribute that is used to provide details about how model binding to a parameter should occur in ASP.Net MVC.

Bind attribute is another important security mechanism that keeps hackers from over-posting data to your model. You should only include properties in the bind attribute that you want to change.

For example, suppose the Student entity includes a Secret property that you don't want this web page to update.

   public class Student
   {
      public int ID { get; set; }
      public string LastName { get; set; }
      public string FirstMidName { get; set; }
      public DateTime EnrollmentDate { get; set; }
      public string Secret { get; set; }

      public virtual ICollection<Enrollment> Enrollments { get; set; }
   }

Even if you don't have a Secret field on the web page, a hacker could use a tool such as  fiddler, or write some JavaScript, to post a Secret form value. Without the  Bind attribute limiting the fields that the model binder uses when it creates a Student instance, the model binder would pick up that Secret form value and use it to update the Student entity instance. Then whatever value the hacker specified for the Secret form field would be updated in your database. The following image shows the fiddler tool adding the Secret field (with the value "OverPost") to the posted form values.



The value "OverPost" would then be successfully added to the Secret property of the inserted row, although you never intended that the web page be able to update that property.

It's a security best practice to use the Include parameter with the Bind attribute to whitelist fields. It's also possible to use the Exclude parameter to blacklist fields you want to exclude. The reason Include is more secure is that when you add a new property to the entity, the new field is not automatically protected by an Exclude list.

Display Modes in ASP.NET MVC | Detecting Device Type Using Display Modes in ASP.NET MVC | ASP.NET MVC Programmer Guide

Display modes are extremely useful in any scenario where multiple views for the same action can be selected based on run time conditions.

Display Mode is logically the same as a style sheet except that it deals with HTML views instead of CSS styles. A display mode is a query expression that selects a specific view for a given controller action. In much the same way, the Web browser on the client processes CSS media query expressions and applies the appropriate style sheet; a display mode in server-side ASP.NET MVC processes a context condition and selects the appropriate HTML view for a given controller action.
Display modes are extremely useful in any scenario where multiple views for the same action can be selected based on run-time conditions. The most compelling scenario, however, is associated with server-side device detection and view routing. By default, starting with ASP.NET MVC 4, any Razor view can be associated with a mobile-specific view. The default controller action invoker automatically picks up the mobile-specific view if the user agent of the current request is recognized as the user agent of a mobile device. This means that if you have a pair of Razor views such as index.cshtml and index.mobile.cshtml, the latter will be automatically selected and displayed in lieu of the former if the requesting device is a mobile device. This behavior occurs out of the box and leverages display modes. Display modes can be customized to a large extent. Here’s an example:
var tablet = new DefaultDisplayMode("tablet")
{
   ContextCondition = (c => IsTablet(c.Request))
};
var desktop = new DefaultDisplayMode("desktop")
{
   ContextCondition = (c => return true)
};
displayModes.Clear();
displayModes.Add(tablet);
displayModes.Add(desktop);
The preceding code goes in the Application_Start event of global.asax and clears default existing display modes and then adds a couple of user-defined modes. A display mode is associated with a suffix and a context condition. Display modes are evaluated in the order in which they’re added until a match is found. If a match is found—that is, if the context condition holds true—then the suffix is used to complete the name of the view selected. For example, if the user agent identifies a tablet, then index.cshtml becomes index.tablet.cshtml. If no such Razor file exists, the view engine falls back to index.cshtml.

Sections in ASP.NET MVC Layout Page | ASP.NET MVC Programmer Guide | ASP.NET MVC Tutorial

In ASP.NET MVC, a layout page consists of sections. A section is an area that derived pages can override. You might want to use this feature to let each page specify CSS and script (and of course markup) that needs be specific. Each layout must contain at least the section for the body.
<div class="container">
    @RenderBody()
    <hr />
    <footer>
        © @DateTime.Now.Year - ASP.NET QuickUp
    </footer>
</div>
The markup above indicates that the entire body of the page replaces @RenderBody. You can define custom sections in a layout file using the following line:
@RenderSection("CustomScripts")
The name of the section is unique but arbitrary and you can have as many sections as you need with no significant impact on the rendering performance. You just place a @RenderSection call where you want the derived page to inject ad hoc content. The example above indicates a section where you expect the page to insert custom script blocks. However, there’s nothing that enforces a specific type of content in a section. A section may contain any valid HTML markup. If you want to force users to add, say, script blocks, you can proceed as follows:
<script type="text/javascript">
   @RenderSection("CustomScripts")
</script>
In this case, overridden sections are expected to contain data that fits in the surrounding markup; otherwise, a parsing error will be raised. In a derived page, you override a section like this:
@section CustomScripts
{
   alert("Hello");
}

Naming Conventions in Creating Partial Views in ASP.NET MVC | ASP.NET MVC Programmer Guide

When creating partial views, it is important to follow the prescribed naming convention for the sake of consistency. In the naming convention for partial views, the file name begins with an underscore and is suffixed by Partial. For example, the partial view for ArtistInfo would be named _ArtistInfoPartial.cshtml.

While the underscore has no technical ramifications in the MVC Framework, it does have significance in  ASP.NET WebPages—where the convention originated. The Partial suffix tells other developers that the file is intended to function as a partial view.

ASP.NET MVC Layout Page Best Practices | Recommendations in Implementing ASP.NET MVC Layout Page | ASP.NET MVC Programmer Guide

In ASP.NET MVC, a layout file is what a master page was in classic Web Forms: the blueprint for multiple pages that are ultimately built out of the provided template. 
With the exceptions and variations mentioned a moment ago for parallelizing the download of multiple scripts, there are two general rules that hold true for the vast majority of websites. The first rule says: Place all of your CSS in the HEAD element. The second rule says: Place all of your script elements right before the closing tag of the <body> element.

Behind Bundling and Minification of Stylesheets in ASP.NET MVC | Bundling and Minification Tutorial | ASP.NET MVC Programmer Guide

Too many requests from a single HTML page may cause significant delays and affect the overall time-to-last-byte metrics for a site. Bundling is therefore the process of grouping distinct resources such as CSS files into a single downloadable resource. In this way, multiple and logically distinct CSS files can be downloaded through a single HTTP request.

Assemblies Required to Run ASP.NET MVC Application | ASP.NET MVC Programmer Guide | ASP.NET MVC Tutorial

Below figure shows what assemblies you need to have referenced in order to run a dummy ASP.NET MVC application.

Basic Nuget Packages Required in ASP.NET MVC | Nuget Packages to Run ASP.NET MVC Application | ASP.NET MVC Programmer Guide | ASP.NET MVC Tutorial

Below is the minimal collection of Nuget packages you need in ASP.NET MVC Application.
<packages>
  <package id="Microsoft.AspNet.Mvc"
           version="5.0.0"
           targetFramework="net45" />
  <package id="Microsoft.AspNet.Razor"
           version="3.0.0"
           targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages"
           version="3.0.0"
           targetFramework="net45" />
</packages>

Changing the Controller Suffix to Something Else in ASP.NET MVC | ASP.NET MVC Programmer Guide

In ASP.NET MVC, the Inspection whether a given Type qualifies as a controller happens inside DefaultActionDiscoveryConventions, the default IActionDiscoveryConventionsimplementation, inside of the IsController method. So we should either implement IActionDiscoveryConventionsimplementation interface ourself, or extend the DefaultActionDiscoveryConventions, which exposes all of its methods as virtual.

Converting a POCO Class as Controller in ASP.NET vNext | ASP.NET MVC Programmer Guide | ASP.NET MVC Tutorial

In vNext of ASP.NET MVC is the ability to use POCO classes as controllers. No need to inherit a controller class.
By default, as long as your class is public, non-abstract, has a Controller suffix and is defined in an assembly that references any of the MVC assemblies (Microsoft.AspNet.Mvc.Core, Microsoft.AspNet.Mvc etc), it will be discovered as a valid controller. An example is shown below.

Improved Attribute Routing in ASP.NET MVC 5.2 | Whats New in ASP.NET MVC 5.2 | ASP.NET MVC Tutorial

Attribute Routing now provides an extensibility point called IDirectRouteProvider, which allows full control over how attribute routes are discovered and configured. An IDirectRouteProvider is responsible for providing a list of actions and controllers along with associated route information to specify exactly what routing configuration is desired for those actions. An IDirectRouteProvider implementation may be specified when calling MapAttributes/MapHttpAttributeRoutes.

How to Specifying that a Parameter is Optional in MVC Attribute Routing? | ASP.Net MVC Interview Question

, ,
  • You can do it by Specifying that a parameter is Optional (via the '?' modifier).
  • This should be done after inline constraints.
  • Well,it's like this  [Route("Pet/{message:maxlength(4)?}")]
              
        PetController.cs

        // eg: /Pet/good
        [Route("Pet/{message:maxlength(4)?}")]
        public ActionResult PetMessage(string message)
        {
            return View();
        }

Key points of the above code
  • In the above example, /Pet/good and /Pet will Route to the PetMessage Action.
  • The route /Pet also works hence of the Optional modifier.
  • But /Pet/good-bye will not route above Action , because of the maxlength(4) constraint.

Above Routes on Browser are as below

parameter is Optional

How to Apply Multiple constraints to a Parameter in MVC Attribute Routing? | ASP.Net MVC Interview Question

, ,
  • You can apply multiple constraints to a parameter, separated by a colon.
  • Well,It's like this  [Route("Pet/{petId:int:min(1)}")]

 PetController.cs

     public class PetController : Controller
      {
        // eg: /Pet/8
        [Route("Pet/{petId:int:min(1)}")]
        public ActionResult GetSpecificPetById(int petId)
        {
            return View();
         }
     }

Key points of the above code
  • In the above example,You can't use  /Pet/10000000000 ,because it is larger than int.MaxValue
  • And also you can't use /Pet/0 ,because of the min(1) constraint.

How to set Route Constraints ? | ASP.Net MVC Interview Question

, ,
  • It allows you to restrict the parameters in the route template are matched
  • The syntax is {parameter:constraint}

     PetController.cs

     public class PetController : Controller
      {
        // eg: /Pet/8
        [Route("Pet/{petId:int}")]
        public ActionResult GetSpecificPetById(int petId)
        {
            return View();
         }
     }


Key points of the above code
  • In the above example, /Pet/8 will Route to the GetSpecificPetById Action.
  • Here the route will only be selected, if the "petId" portion of the URI is an integer.

Above Route on Browser is as below

Route Constraints





The following diagram shows the constraints that are supported

constraints list

Advantages of Attribute Routing Over the Convention-based Routing | ASP.NET MVC Interview Question

, ,
  • Attribute Routing gives you more control over the URIs in your web application
  • Easy to Troubleshoot issues
  • No fear of modifying anything will break another route down the line 

How to Assign Names to Routes? | ASP.Net MVC Interview Question

, ,
  • Specify a Name for a Route
  • By using that Name, you can easily allow URI generation for it
  • Well,It's like this : [Route("Booking", Name = "Payments")]

  BookingController.cs

 public class BookingController : Controller
    {
        // eg: /Booking
        [Route("Booking", Name = "Payments")]
        public ActionResult Payments() { return View(); }
    }

  • After that you can generate a Link is using Url.RouteUrl
  • It's like this : 
    <a href="@Url.RouteUrl("Payments")">Payments Screen</a>

Note : On the above code, "Payments" is a Route Name

How to override Default Route ? | ASP.Net MVC Interview Question

, ,
  • Use specific [Route] on a specific Action.
  • It'll override the default settings on the Controller.

       BookingController.cs

    [RoutePrefix("Booking")]
    [Route("{action=index}")]
    public class BookingController : Controller
    {
        // eg: /Booking
        public ActionResult Index() { return View(); }

        // eg: /Booking/Edit/3
        [Route("Edit/{bookId:int}")]
        public ActionResult Edit(int bookId) { return View(); }

    }

Above overridden Route on Browser is as below