Wednesday 16 August 2017

How to solve - No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access. In angular js?


It gives error because localhost for mvc and webapi both will have different port then it will error

/// <reference path="angular.min.js" />
var app = angular.module('myApp', []);
app.controller('RegController', function ($scope, $http) {
    $http({
        method:"GET",
        url: 'http://localhost:40477/api/Values/2'
    }).then(function mySuccess(response) {

        $scope.valueData = response.data;
    });

});


-Go to the manage package nuget for solution and type cors and install it then add the namespace in webapi.config- add two lines of code-
 var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace BookTicketService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

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

No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0