Enabling Cross-Origin Requests in ASP.NET5
July 28, 2015 by Anuraj
.Net ASP.Net ASP.Net MVC HTML5 Javascript Web API
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated. “Cross-domain” AJAX requests are forbidden by default because of their ability to perform advanced requests (POST, PUT, DELETE and other types of HTTP requests, along with specifying custom HTTP headers) that introduce many cross-site scripting security issues. CORS defines a way in which a browser and server can interact to safely determine whether or not to allow the cross-origin request. It allows for more freedom and functionality than purely same-origin requests, but is more secure than simply allowing all cross-origin requests. It is a recommended standard of the W3C.
Here is the server controller file, which is exposing a GET method, which returns a user object.
And here is a client side script, which get this data from another web page using JQuery Ajax method.
Without enabling CORS, the ajax request will fail, it will throw some exception like this.
To enable CORS in ASP.NET 5, you need to install the “Microsoft.AspNet.Cors” package to the project.json. And you need to configure CORS in the Startup.cs file.
Here you are Adding the core support and configure ASP.NET to accepts requests from the configured URL. Now if you run the code, you will see “[object Object]” instead of “error” in the label.
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub