Thursday, 26 March 2015

Overriding default HTML encoding in jQuery Template

${template-variable} syntax of jQuery Template encodes the HTML if present in the value passed to the template. You can override the default encoding behaviour using {{html template-variable-containing-html}} instead of the ${template-variable} syntax. Here is an example.


<div id="container">
    <script id="sampleTemplate" type="text/x-jquery-tmpl">
        <div id="cust_${id}">
        <span>${name}</span>:
      
       {{html phone}}

    </script>
</div>

<script type="text/javascript">

$(document).ready(function() {
 
var customer = {
            id: 101, 
            name: 'Test',
            phone: '<b>123-456-777</b><br/><b>111-223-455</b>'
        };

$('#sampleTemplate').tmpl(customer).appendTo('#container');

});

</script>

Monday, 9 March 2015

How to iterate through Microsoft Enterprise Library CacheManager?

Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager doesn't have a method / property that allow you retrieve the entire Cache items together. I had such a requirement and found a work around. This is using reflection to get "realCache" field in CacheManager and then looping through Cache.CurrentCacheState.

GetData() retrieves a single item from the Cache.

ICacheManager cacheManager = CacheFactory.GetCacheManager("cacheName");
object cacheItem = cacheManager.GetData("cacheKey");

Retrieving and iterating the entire Cache


using Microsoft.Practices.EnterpriseLibrary.Caching;

... 

string cacheName = "your-cache-name";
Cache cache;

if (TryGetCache(cacheName, out cache))
{
  foreach (DictionaryEntry cacheEntry in cache.CurrentCacheState)
  {
    object key = cacheEntry.Key;
    CacheItem cacheItem  = (CacheItem)cacheEntry.Value;
    object value = cacheItem.Value;
    Console.WriteLine("{0}: {1}", key, value)
  }
}

private static bool TryGetCache(string cacheName, out Cache cache)
{
  try
  {
    ICacheManager _cacheManager = CacheFactory.GetCacheManager(cacheName);
    cache = (Cache)_cacheManager.GetType().GetField("realCache", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(_cacheManager);
  }
  catch (Exception)
  {
    cache = null;
    return false;
  }
  return true;
}

Thursday, 5 March 2015

DateTime format strings in .NET

A date and time format string defines the text representation of a DateTime that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time. A custom format string consists of one or more custom date and time format specifiers.

Usually a format string is used with DateTime.ToString() or string.Format()

Examples

// DateTime to String

DateTime.Today.ToString("MMM dd, yyyy") // Mar 05, 2015

string.Format("{0:dd/MM/yy HH:mm:ss}", DateTime.Now) // 05/03/2015 14:05:33

string.Format("{0:hh:mm:ss tt}" , DateTime.Now) // 02:05:33 PM

// String to DateTime

string dateString = "Mar 05, 2015";
DateTime dateTime = DateTime.ParseExact(dateString , "MMM dd, yyyy", null);

Format Specifiers cheat sheet
Day of the month - "d", "dd"

Name of the day of the week - "ddd", "dddd" 

Month - "M", "MM", "MMM", "MMMM"

Year - "y", "yy", "yyy", "yyyy"

Hour (12 hour clock) - "h", "hh"

Hour (24 hour clock) - "H", "HH"

AM/PM designator - "t", "tt"

Minute - "m", "mm"

Second - "s", "ss"

MSDN >>

Download DateTime Formatting Utility from Microsoft : The Format Utility (Formatter.exe) is a Windows Forms application that allows you to apply standard or custom format strings to either numeric values or date and time values and to determine how they affect the result string.

Friday, 27 February 2015

Unit Testing ASP.NET MVC - Cheat Sheet

Mocking Request Cookie
var mockContext = new Mock<ControllerContext>();

mockContext.Setup(c => c.HttpContext.Request.Cookies).Returns(new HttpCookieCollection { new HttpCookie("test", "1") });

HomeController controller = new HomeController();
controller.ControllerContext = mockContext.Object;

var result = controller.Index()
Mocking Response Cookie
var mockContext = new Mock<ControllerContext>();

mockContext.SetupGet(c => c.HttpContext.Response.Cookies).Returns(new HttpCookieCollection());

HomeController controller = new HomeController();
controller.ControllerContext = mockContext.Object;

var result = controller.Index()

Assert.AreEqual(controller.ControllerContext.RequestContext.HttpContext.Response.Cookies["test"].Value, "1");

Mocking Request.IsAuthenticated
var mockContext = new Mock<ControllerContext>();
mockContext.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mockContext.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);

var controller = new HomeController();
controller.ControllerContext = mockContext.Object;
Mocking ModeState.IsValid

ModeState.IsValid property is read only. But you can add an error to the ModelState to set the IsValid flag false indirectly.

var controller = new HomeController();
controller.ModelState.AddModelError("Error", "Model is invalid");
ViewResult result = controller.Index() // ModeState.IsValid will be false when Index() is executed. 
Mocking Dependency

MathController depends on an implementation of IMathService to complete the action. In the following example a mock instance of IMathService is passed to MathController to test the Add() method

Mock mathService = new Mock<IMathService>();
mathService.Setup(ms => ms.Add(1, 2)).Returns(3);

MathController controller = new MathController(mathService.Object);
var result = controller.Index(1, 2) as ViewResult;

Assert.AreEqual(result.ViewBag.Sum, 3);
mathService.Verify(ms => ms.Add(1,2), Times.Exactly(1));
Mocking Exception
Mock mathService = new Mock<IMathService>();
mathService.Setup(ms => ms.Add(1, 0)).Throws(new ArgumentException("Invalid argument(s)"));

MathController controller = new MathController(mathService.Object);

try
{
      var result = controller.Index(1, 0) as ViewResult;
}
catch(ArgumentException ex)
{
      Assert.AreEqual("Invalid argument(s)", ex.Message);
}
Testing RedirectResult

If your method returns a RedirectResult then you can check the result url against the expected

var controller = new RedirectController();

RedirectResult result = controller.SendMeSomewhereElse();

Assert.AreEqual("~/Some/Other/Place", result.Url);
Testing RedirectToRouteResult

If your method returns a RedirectToRoute i.e. if your action method returns RedirectToAction() or RedirectToRoute() then you can check the action name in RouteValues against the expected value. In the following example CustomerController.Create() is tested to check if the request is redirected to Index after creating the customer.

 var controller = new CustomerController();

var result = controller.Create(new Customer {Name = "Test"}) as RedirectToRouteResult;

Assert.AreEqual("Index", result.RouteValues["action"]);

Mocking HttpContext

Click here to see how to Mock HttpContext

Friday, 13 February 2015

ActionResult types in ASP.NET MVC

ActionResult (System.Web.Mvc.ActionResult) Subtypes

ContentResult - Returns a user-defined content type.

Helper method: System.Web.Mvc.Controller.Content()

EmptyResult - Represents a return value that is used if the action method must return a null result (void).

Helper method: (None)

FileContentResult - Sends the contents of a binary file to the response.

Helper method: System.Web.Mvc.Controller.File()

FileStreamResult - Sends binary content to the response through a stream.

Helper method: System.Web.Mvc.Controller.File()

FilePathResult - Sends the contents of a file to the response.

Helper method: System.Web.Mvc.Controller.File()

HttpStatusCodeResult - Returns a specific HTTP response code and description.

Helper method: (None)

HttpUnauthorizedResult - Returns the result of an unauthorized HTTP request.

Helper method: (None)

HttpNotFoundResult - Indicates the requested resource was not found.

Helper method: System.Web.Mvc.Controller.HttpNotFound()

JavaScriptResult - Returns a script that can be executed on the client.

Helper method: System.Web.Mvc.Controller.JavaScript()

JsonResult - Returns a serialized JSON object.

Helper method: System.Web.Mvc.Controller.Json()

PartialViewResult - Renders a partial view, which defines a section of a view that can be rendered inside another view.

Helper method: System.Web.Mvc.Controller.PartialView()

RedirectResult - Redirects to another action method by using its URL.

Helper method: System.Web.Mvc.Controller.Redirect()

RedirectToRouteResult - Redirects to another action method.

Helper method: System.Web.Mvc.Controller.RedirectToAction() or RedirectToRoute()

ViewResult - Renders a view as a Web page.

Helper method: System.Web.Mvc.Controller.View()

MSDN >>

Wednesday, 11 February 2015

How to add a section conditionally in ASP.NET MVC?

Here you go

@if(sectionRequired)
{
@:@section OptionalSection
{
<div class="content">
  Some text
</div>
}
}

You can set the Razor variable sectionRequired as required.

Deep cloning objects in JavaScript

There are a lot of ways to clone objects in Javascript and here are two of them.

Using JSON library

var person = {
    name: "Jack",
    age: 21,
    address: {houseNumber: 11, postcode: 'BR3'}
};
 
var jill = (JSON.parse(JSON.stringify(person)));
jill.name = "Jill";
 
console.log(person);
console.log(jill);

Using jQuery’s $.extend()

var person = {
    name: "Jack",
    age: 21,
    address: {houseNumber: 11, postcode: 'BR3'}
};
 
var jill = $.extend(true, {}, person);
jill.name = "Jill";
 
console.log(person);
console.log(jill);

$.extend() method is a little slower than the JSON exploit, but that shouldn’t really be a problem when you’re only doing a few clones.

Click here to read more

Using anonymous function as an alias to jQuery DOMReady function

Below syntax is a shorthand to jQuery.ready() function. The anonymous function passed to jQuery is only a callback function, it won't considered as a "JavaScript Module".

$(function(){
  
});

I.e. it does exactly the same thing that the below code block does, specify a function to execute when the DOM is fully loaded.

$(document).ready(function(){
  
});

But even though below code looks similar to the first syntax its is treated differently. This is called as module pattern or immediately invoking function in JavaScript

(function($) {
  
})(jQuery);

  • A module pattern or immediately invoking function executes immediately after it’s defined. It does not wait for the DOM to be ready.
  • Passing jQuery in to the parenthesis is to provide local scoping to the global variable.
  • All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.
  • To allow external code to access to a variable or function we can expose it to the global ‘window’ object.
    (function(){
      var foo = 'Hello';
      var bar = 'World!'
      
      function baz(){
          return foo + ' ' + bar;
      }
    
      window.baz = baz; //Assign 'baz' to the global variable 'baz'...
    })();
    
    console.log(baz()); 
    
Modules are a pattern of implementation that use an immediately invoking function to provide scope and privacy around a “module” of related functionality.

Click here to read more about JavaScript Module Pattern.

If the anonymous function passed to the DOM ready() method has lot of code in it then you can use an object literal to organize the handles and callbacks as shown in below example.

var dom = {
 
    onReady: function() {
        $( "#btn1" ).click( dom.animate);
    },
 
    animate: function( event ) {
        $( "#yayeffects" ).toggle();
    } 
};
 
$( document ).ready( dom.onReady );

Wednesday, 4 February 2015

jQuery - How to get Html including the selector?

As you know jQuery .html() method can be used to get the HTML contents of the first element in the set of matched elements. But sometimes you might want to get the HTML including the container as well.

For example if you have below html

<div id="container">
 <div id="content">jQuery is awesome</div>
</div>

and if you use $('#container').html() it will give you

<div id="content">jQuery is awesome</div>
i.e. it returns the "innerHTML" of the "container" DIV.

There are many workarounds to it i.e. to get html including the "container".

Using wrap()

If you wrap the container in a dummy P tag you will get the container HTML as well.

var outerHtml  = $('#container').wrap('<p/>').parent().html();
Using clone()
var outerHtml = $("<div />").append($('#container').clone()).html();

Using wrap actually affects the DOM tree displayed to the user. This doesn't.

Tuesday, 27 January 2015

jQuery Ajax Cheat Sheet

jQuery.ajax( url [, settings ] ) performs an Asynchronous HTTP (Ajax) requests using jQuery.

Basic settings

Url

$.ajax({url: '/Products/Details/1234' })

Querystring

$.ajax({url: '/Products/Details?id=1234&showorders=false' })

type: HTTP Method

$.ajax({url: '/Products/Details/1234', type: 'POST' })

data: Data to be sent to the server.It is converted to a query string, if not already a string. It's appended to the url for GET-requests.

$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234} })

$.ajax({url: '/Products/Details', type: 'POST', data: $('form1').serialize() })

var contact = {firstName:"Bob", lastName:"Bob", mobile:"9907833", email: "bob@example.com"};
$.ajax({url: '/Contact/Create', type: 'POST', data: JSON.stringify(contact) })

contentType: Type of data send to the server

default value is 'application/x-www-form-urlencoded; charset=UTF-8'
$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234}, contentType: 'application/json; charset=UTF-8' })

dataType: type of data expecting from server. If none is specified, jQuery will try to infer it based on the MIME type of the response - xml, json, script, or html

$.ajax({url: '/Products/Details', type: 'POST', data: {id: 1234}, dataType: 'html' })

headers: Helps to set http header(s)

$.ajax({url: '/Products/Details', headers: { Accept: "application/json; charset=utf-8", "Content-Type": "application/x-www-form-urlencoded" }, data: $('form1').serialize() })

Handling succeeded request/response

$.ajax({url: '/Products/Details?id=1234',  
               success: function (result, textStatus, jqXHR) {
                    alert("success");
                }
})

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second complete" );
});

Handling failed request/response.

$.ajax({url: '/Products/Details?id=1234',  
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus);alert(jqXHR.status);alert(errorThrown);
                }  })

Handling response based of HTTP status code

$.ajax({url: '/Products/Details?id=1234',  
               
statusCode: {
                    201: function (s) {
                        $('#result').html(s);
                    },
                    404: function () {
                        alert("Not Found!");
                    }
                }
})

Ajax Shorthand Methods

jQuery.get() Load data from the server using a HTTP GET request.

$.get( "test.php", function( data ) { $( "body" ).append(data) });

jQuery.getJSON() Load JSON-encoded data from the server using a GET HTTP request.

(function() {
$.getJSON( "example.json", function() {
  console.log( "success" );
})
.done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "" ).attr( "src", item.media.m ).appendTo( "#images" );
      });
    });
})();

jQuery.getScript() Load a JavaScript file from the server using a GET HTTP request, then execute it. jQuery.getScript() sets cache to false by default.

$.getScript("/jscript/test.js")

jQuery.post() Load data from the server using a HTTP POST request. Pages fetched with POST are never cached, so the cache and ifModified options in jQuery.ajaxSetup() have no effect on these requests.

$.post( "/product/list", function( data ) {
  $( ".result" ).html( data );
});

jQuery.load() Load data from the server and place the returned HTML into the matched element.

$( "#result" ).load( "/product/list" );

Thursday, 22 January 2015

Html helper extension method for creating pagination links in ASP.NET MVC

Add below Extension method to your project
using System;
using System.Web.Mvc;
using System.Text;

namespace YourWebUI.HtmlHelpers
{
    public static class PagingHelpers
    {
        public static MvcHtmlString PageLinks(this HtmlHelper html, int totalPages, Func pageUrl)
        {
            StringBuilder pageLinks = new StringBuilder();
            for (int i = 1; i <= totalPages; i++)
            {
                TagBuilder pageLink = new TagBuilder("a");
                pageLink.MergeAttribute("href", pageUrl(i));
                pageLink.InnerHtml = i.ToString();
                pageLinks.Append(pageLink.ToString());
                pageLinks.Append(i == totalPages? "" : " | ");
            }
            return MvcHtmlString.Create(pageLinks.ToString());
        }
    }
}
Add the namespace YourWebUI.HtmlHelpers to web.config
  <system.web.webPages.razor>
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        ...
        <add namespace="YourWebUI.HtmlHelpers"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>
Razor syntax for calling the method
 @Html.PageLinks(5, x => Url.Action("Index", new { page = x }))
Sample output
<a href="/?page=1">1</a> | <a href="/?page=2">2</a> | <a href="/?page=3">3</a> | <a href="/?page=4">4</a> | <a href="/?page=5">5</a>
Click Here to see a different way of doing this.

Wednesday, 22 October 2014

What is the difference between iisreset, recycle, refresh and restart?

iisreset

iisreset will stop and start the World Wide Web Publishing Service. This, of course, applies to all of your application pools.

Recycle application pool

A process being created for each application pool. This process will handle requests for all websites associated with it. When you recycle an application pool, IIS will create a new process (keeping the old one) to serve requests. Then it tries to move all requests on the new process. After a time-out the old process will be killed automatically.

You usually recycle your application pool to get rid of leaked memory. You might have a problem in your application if this needs to be a regular operation. It is recommended to have a scheduled recycle.

Restarting a website

As for restarting a website, it just stops and restarts serving requests for that particular website. It will continue to serve other websites on the same app pool with no interruptions.

If you have a session oriented application, all of the above will cause loss of session objects.

Refreshing IIS or a website

Refreshing a website has no effect on the service/process/website and is merely a UI command to refresh the tree-view. For example you have added a directory that you don't see in the management console. Then refreshing the website will show the new directory in the treeview.

Tuesday, 21 October 2014

Difference between jQuery.bind() and jQuery.on()?

.on() is a new function available from jQuery version 1.7. .on() can be used to attach an event handler function for one or more events of the selected elements.

The .on() method provides all functionality required for attaching event handlers. So on() is now preferred over other event handling functions .bind(), .delegate() and .live()

Syntax
.on( events [, selector ] [, data ], handler )
Notes

To remove events bound with .on() use .off(). To attach an event that runs only once and then removes itself use .one()

on() vs bind()

These two lines are functionally the same

    $( '#element' ).bind( 'click', handler );
    $( '#element' ).on( 'click', handler );

.on() can also do event delegation, and is preferred.

.bind() is actually just an alias for .on() now. Here's the definition of the bind function in 1.7.1.

    bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
    }

Friday, 10 October 2014

How to render partial view from different folder?

The usual syntax to render a partial view is

@Html.Partial("partialViewName")

This syntax expects the partial view to be physically present in the current folder or in the "Shared" folder.

If you want to use a partial view which is not in "Shared" but in a different "Views" folder then use below Razor syntax.

@Html.Partial("~/Views/AnotherFolder/_partialView.cshtml")

How to check for null, undefined, or blank variables in JavaScript?

You can just check if the variable has a true value or not. That means

if( value ) {
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

Furthermore, if you don't know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if( typeof foo !== 'undefined' ) {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you can directly check if it has a true value.

Truth, Equality and JavaScript

JavaScript Coercion Demystified

Wednesday, 1 October 2014

Hashing, MD5, SHA1, Salted Password Hashing

Hashing

Hashing is the transformation of a string of characters into a usually shorter fixed-length value or key that represents the original string. Hashing is used to index and retrieve items in a database because it is faster to find the item using the shorter hashed key than to find it using the original value. It is also used in many encryption algorithms.

A hash function is any function that can be used to map digital data of arbitrary size to digital data of fixed size, with slight differences in input data producing very big differences in output data.

Hash algorithms are one way functions. They turn any amount of data into a fixed-length "fingerprint" that cannot be reversed.

Collision / Hash Collision

The hash function is used to index the original value or key and then used later each time the data associated with the value or key is to be retrieved. Thus, hashing is always a one-way operation. There's no need to "reverse engineer" the hash function by analysing the hashed values. In fact, the ideal hash function can't be derived by such analysis. A good hash function also should not produce the same hash value from two different inputs. If it does, this is known as a collision.

MD5

The MD5 message-digest algorithm is a widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number. MD5 has been utilized in a wide variety of cryptographic applications, and is also commonly used to verify data integrity.

SHA1

SHA1 stands for Secure Hash Algorithm makes a larger (160-bit / 20-byte) message digest and is similar to MD4. A SHA-1 hash value is typically rendered as a 40 digits long hexadecimal number.

Password Hashing

Hashing is great for protecting passwords, because we want to store passwords in a form that protects them even if the password file itself is compromised, but at the same time, we need to be able to verify that a user's password is correct.

The general workflow for an account registration and authentication in a hash-based account system is as follows:

  1. The user creates an account.
  2. Their password is hashed and stored in the database. At no point is the plain-text (unencrypted) password ever written to the hard drive.
  3. When the user attempts to login, the hash of the password they entered is checked against the hash of their real password (retrieved from the database).
  4. If the hashes match, the user is granted access. If not, the user is told they entered invalid login credentials.
  5. Steps 3 and 4 repeat everytime someone tries to login to their account.

In step 4, never tell the user if it was the username or password they got wrong. Always display a generic message like "Invalid username or password." This prevents attackers from enumerating valid usernames without knowing their passwords.

It should be noted that the hash functions used to protect passwords are not the same as the hash functions you may have seen in a data structures course. The hash functions used to implement data structures such as hash tables are designed to be fast, not secure. Only cryptographic hash functions may be used to implement password hashing. Hash functions like SHA256, SHA512, RipeMD, and WHIRLPOOL are cryptographic hash functions.

Salted Password Hashing

We can randomize the hashes by appending or prepending a random string, called a salt, to the password before hashing.The salt does not need to be secret. Just by randomizing the hashes, lookup tables, reverse lookup tables, and rainbow tables become ineffective. An attacker won't know in advance what the salt will be, so they can't pre-compute a lookup table or rainbow table. If each user's password is hashed with a different salt, the reverse lookup table attack won't work either.

Salted Password Hashing - Doing it Right

Friday, 26 September 2014

Is CSS case sensitive?

CSS is case insensitive in all matters under its control; however, some things, such as the document markup language, are beyond its control. HTML is case insensitive in most respects, except when it comes to certain attribute values, like the id and class attributes. XHTML, being XML, is always case sensitive.

The simplest way to mitigate any potential issues surrounding case sensitivity is to always use lowercase for everything in your markup and CSS, where possible. If that’s not possible, make sure the case you use is consistent between your CSS and your document markup.

CSS Case Sensitivity

www.w3.org >> Element identifiers: the id and class attributes

Are class names in CSS selectors case sensitive?

Wednesday, 24 September 2014

How does browsers' same-origin policy (SOP) work?

Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web Service / Web API.

I was under the impression that the request will never go to the server in this scenario. I am sure that many of you would be thinking the same. BUT if you watch the HTTP traffic in a tool like Fiddler, you will see that the browser does send the GET request, and the request succeeds, but the AJAX call returns an error. It’s important to understand that same-origin policy does not prevent the browser from sending the request. Instead, it prevents the application from seeing the response.

Now you can use a mechanism called CORS i.e Cross-Origin Resource Sharing, to enable client-side cross-origin requests.

Cross-Origin Requests in ASP.NET Web API

Cross-Origin Requests in ASP.NET Web API

Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy, and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.

Cross Origin Resource Sharing (CORS) is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others. CORS is safer and more flexible than earlier techniques such as JSONP. Follow below links to see how to enable CORS in your Web API application.