Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

.NETWeb API
Home›.NET›Fix To No Access-Control-Allow-Origin header is present Or Working With Cross Origin Request In Asp Net Web API

Fix To No Access-Control-Allow-Origin header is present Or Working With Cross Origin Request In Asp Net Web API

By SibeeshVenu
March 11, 2016
20869
11
Share:
Configured_Web_API_in_IIS

[toc]

Introduction

In this article we are going to few possible fixes we can apply when we get an error “Response to the preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:58018’ is therefore not allowed access”. We get this error when we are trying to get some data from another origin may be via an AJAX call. In this post, we will discuss the solutions for this error in detail and we will also discuss Cross Origin Requests. Here I am going to use Visual Studio 2015, Web API 2. I hope you will like this.

Background

I hosted my Web API in a server, and what that API does is, it will just return the data in JSON format. But when I try to consume this Web API via an Ajax call, I was getting the error “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”. I solved the same issues in different ways. Here I am going to share those.

Using the code

I assume that you have created a Web API and hosted it in your server. If you are new to Web API, you can always get some information from here Articles Related To Web API .

We all will have some situations where we need to fetch some data from another domain or another site, right? If it is from the same site, you won’t be facing any issues at all. Like you are calling an Ajax call from the page www.sibeeshpassion.com/Receiver.html to www.sibeeshpassion.com/Sender.html to get the data, here the origin is same. and therefore you will get the data. What happens is when the sender and receiver are not in the same origin. Like you need to get the data from www.Microsoft.com by an Ajax call in www.sibeeshpassion.com/Receiver.html. The browser will not allow you to get the sensitive data from other domain, for the security purpose your browser will return you “No ‘Access-Control-Allow-Origin'”. To overcome this, we have something called Cross-Origin Resource Sharing (CORS). Basically, the process of allowing other sites to call your Web API is called CORS. According to W3 Org CORS is a standard which tells the server to allow the calls from other origins given. It is much secured than using JSONP(Previously we had been using JSON for getting the data from other domains.).

Fix To No Access-Control-Allow-Origin header is present

We can fix this issue in two ways,

  • By using Microsoft.AspNet.WebApi.Cors
  • By adding header information in Web.config

We will explain both now.

By using Microsoft.AspNet.WebApi.Cors

To work with this fix, you must include the package By using Microsoft.AspNet.WebApi.Cors from Manage Nuget window.

CORS_In_Manage_NuGet_Package

CORS_In_Manage_NuGet_Package

Now got to App_Start folder from your solution. Then click on the file WebApiConfig.cs, this is the file where we set the configuration for our Web API.

Web_API_Config_Class_File

Web_API_Config_Class_File

Then you can add the preceding codes in the static function Register.

[csharp]
var cors = new EnableCorsAttribute(“*”, “*”, “*”);
config.EnableCors(cors);
[/csharp]

IF you do this, the CORS will be applied globally for all the Web API controller you have. This is the easiest way of doing it. Now if you want to see the metadata of EnableCorsAttribute, you can see find it below.

[csharp]
// Summary:
// Initializes a new instance of the System.Web.Http.Cors.EnableCorsAttribute class.
//
// Parameters:
// origins:
// Comma-separated list of origins that are allowed to access the resource. Use
// “*” to allow all.
//
// headers:
// Comma-separated list of headers that are supported by the resource. Use “*” to
// allow all. Use null or empty string to allow none.
//
// methods:
// Comma-separated list of methods that are supported by the resource. Use “*” to
// allow all. Use null or empty string to allow none.
public EnableCorsAttribute(string origins, string headers, string methods);
[/csharp]

As it is mentioned, it accepts the parameters origins, headers, methods. Here we pass * to all the three parameters to make everything to be allowable.

You can also try the same as below in the Register function. Here we are going to apply CORS for particular controller, which means it will be applied for all the actions in the controller. Before that make sure you have added the preceding code in your WebApiConfig.cs file

[csharp]
config.EnableCors();
[/csharp]

And in the API controller you need to set the origins,headers,methods as preceding.

[csharp]
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using System.Web.Http.Cors;

namespace APIServiceApplication.Controllers
{

[EnableCors(origins: “*”, headers: “*”, methods: “*”)]
public class DefaultController : ApiController
{
}
}

[/csharp]

Make sure that you have added namespace using System.Web.Http.Cors; to use CORS. You can always disable CORS in an action by using [DisableCors].

[csharp]
namespace APIServiceApplication.Controllers
{

[EnableCors(origins: “*”, headers: “*”, methods: “*”)]
public class DefaultController : ApiController
{
[DisableCors]
public string XMLData(string id)
{
return “Your requested product” + id;
}
}
}
[/csharp]

Here we have disabled CORS for the action XMLData. And again if you need to apply CORS only in a single action, you can do that as follows.

[csharp]
namespace APIServiceApplication.Controllers
{
public class DefaultController : ApiController
{
[EnableCors(origins: “*”, headers: “*”, methods: “*”)]
public string XMLData(string id)
{
return “Your requested product” + id;
}
}
}
[/csharp]

I hope you are aware of how to enable CORS now.

By adding header informations in Web.config

Another fix we can do is that add some tags in our Web.config file.

[html]
<system.webServer>
<httpProtocol>
<customHeaders>
<add name=”Access-Control-Allow-Origin” value=”*” />
<add name=”Access-Control-Allow-Headers” value=”Content-Type” />
<add name=”Access-Control-Allow-Methods” value=”GET,POST,PUT,DELETE,OPTIONS” />
<add name=”Access-Control-Allow-Credentials” value=”true” />
</customHeaders>
</httpProtocol>
</system.webServer>
[/html]

As you can see we have added keys with value for the listed items.

  • Access-Control-Allow-Origin (For Origin)
  • Access-Control-Allow-Headers (For Headers)
  • Access-Control-Allow-Methods (For Methods)

Now if you go to your server and check, you can see that all the things are configured perfectly. I have configured my API in my server IIS, so I am going to see my Response Header settings in IIS.

Go to the command window and type “inetmgr” and click OK, your IIS wilbe openeded shortly, now find your Web API which you have already configured under Default Web Site. Before doing this, please make sure that you have configured IIS in your windows. If you don’t know how to configure, I strongly recommend you to read Configure IIS in Windows .

Configured_Web_API_in_IIS

Configured_Web_API_in_IIS

Go to Features View and double click on HTTP Response Headers under IIS category.

HTTP_Response_Headers_In_IIS

HTTP_Response_Headers_In_IIS

You can see all the settings has been configured there.

HTTP_Response_Headers_Available

HTTP_Response_Headers_Available

CORS in Asp.Net Core application

Though the mechanism is the same, the way you do things in Asp.Net core application. To set the CORS in asp.net application, you should add the preceding code in your ConfigureServices method in Startup.cs file before the services.AddMvc(); call.

services.AddCors(cors => cors.AddPolicy("CorsPolicy", builder => {
 builder.AllowAnyHeader()
  .AllowAnyMethod()
  .AllowAnyOrigin();
}));

You should also use this policy you have created in the Configure method in Startup.cs before the app.UseMvc(); call.

app.UseCors("CorsPolicy");

That’s all, now if you run your application, you will be able to fetch the data from your Web API.

Conclusion

Did I miss anything that you may think which is needed? Have you ever faced this issue? Did you try Web API yet? I hope you liked this article. Please share me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I am able to.

Kindest Regards
Sibeesh Venu

TagsConfigure Web API In IISCORSCross Origin Request In Asp Net Web APIIISNo Access-Control-Allow-OriginWeb API
Previous Article

Asp Net Article Of The Day Mar ...

Next Article

Asp Net Article Of The Day Mar ...

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • Add_References
    .NETASP.NETWeb API

    Caching In Web API

    March 24, 2016
    By SibeeshVenu
  • CRUD_in_MVC_Using_Web_API
    .NETMVCVisual StudioWeb API

    Load Data From Database Using Web API

    October 31, 2015
    By SibeeshVenu
  • Test API Client Output With Response
    .NETSQLWeb API

    Working With Test Client In Asp Net Web API Help Page

    May 31, 2016
    By SibeeshVenu
  • jQuery Datatable With Server Side Data
    .NETAngularWeb API

    jQuery Datatable With Server Side Data

    February 25, 2016
    By SibeeshVenu
  • WebApi Config File
    .NETHow toWeb API

    Solutions for the error “the server responded with a status of 405 (method not allowed)”

    February 8, 2016
    By SibeeshVenu
  • Unable to Launch the IIS Express Web Server
    IISMicrosoft

    Solution to “Unable to Launch the IIS Express Web Server”

    January 29, 2015
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version