Programming

Setting Access-Control-Allow-Origin in ASPNet MVC - simplest possible method

25 September 2026 · 9 min read

Setting Access-Control-Allow-Origin in ASPNet MVC - simplest possible method

In today’s interconnected web, web applications frequently need to interact with resources from different origins. This is where Cross-Origin Resource Sharing (CORS) comes into play. Specifically, this article provides the simplest possible method for setting Access-Control-Allow-Origin in ASP.Net MVC applications. We’ll explore various techniques, focusing on ease of implementation and maintainability. Understanding and correctly configuring CORS is crucial for preventing security vulnerabilities and ensuring your ASP.Net MVC application can communicate effectively with other domains. We will explore the most straightforward approaches to enable cross-origin requests, ensuring your application functions smoothly while maintaining robust security practices. This guide aims to demystify CORS configuration, providing you with practical, easy-to-implement solutions.

Understanding Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is a browser security feature that restricts web pages from making requests to a different domain than the one which served the web page. This is a security mechanism to prevent malicious websites from accessing sensitive data from other sites. Without CORS, a website could potentially make requests to your bank’s website on your behalf, which is obviously undesirable. CORS works by adding HTTP headers that tell the browser to grant a web application running at one origin, access to selected resources from a different origin. If the server doesn’t respond with the correct CORS headers, the browser blocks the request, even if the server processes it correctly.

The Access-Control-Allow-Origin header is a critical part of the CORS mechanism. It specifies the origin(s) that are allowed to access the resource. The value can be a specific origin (e.g., https://example.com), or the wildcard character , which allows any origin. While using might seem like the simplest solution, it’s generally not recommended for production environments due to security implications. It essentially disables CORS protection, which could open your application to cross-site scripting (XSS) attacks. For production, it’s better to explicitly list the allowed origins. According to OWASP, improper CORS configuration is a common security misconfiguration [OWASP CORS Guide](https://owasp.org/www-project-top-ten/).

To better understand the implications, consider a scenario where your ASP.Net MVC application exposes an API. A legitimate front-end application hosted on https://my-app.com needs to access this API. Without proper CORS configuration, the browser will block the requests from https://my-app.com to your API’s domain. Setting the Access-Control-Allow-Origin header to https://my-app.com allows the browser to permit these requests, facilitating seamless communication between the front-end and back-end. Misconfiguring CORS can lead to frustrating errors and broken functionality, highlighting the importance of understanding and implementing it correctly.

Simplest Method: Using Web.config

The simplest method for setting Access-Control-Allow-Origin in ASP.Net MVC involves modifying the Web.config file. This approach requires no code changes and can be easily deployed. By adding specific headers in the Web.config file, you can instruct the server to include the Access-Control-Allow-Origin header in every response. This ensures that the browser receives the necessary information to allow cross-origin requests. This method is particularly useful for simple scenarios where you need to enable CORS for all endpoints in your application. The configuration can be easily adjusted by modifying the Web.config file, making it a flexible solution for various deployment environments.

Here’s how to implement it. Open your Web.config file and add the following section within the <system.webServer> section:

<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" /> </customHeaders> </httpProtocol> 

This configuration adds the Access-Control-Allow-Origin header with a value of , allowing requests from any origin. It also sets `Access-Control-Allow-Headers` to `Content-Type`, allowing the `Content-Type` header to be sent in cross-origin requests. Finally, it sets `Access-Control-Allow-Methods` to allow `GET`, `POST`, `PUT`, `DELETE`, and `OPTIONS` methods. While this is the simplest approach, remember to replace with specific origins in a production environment for enhanced security. You should also carefully consider which headers and methods to allow, based on your application’s requirements. For example, if your API only supports GET and POST requests, you should restrict the allowed methods to those two.

Implementing CORS with a Custom Action Filter

For more granular control over CORS, you can implement a custom action filter in ASP.Net MVC. This approach allows you to apply CORS headers to specific actions or controllers, rather than globally. This is beneficial when you only need to enable CORS for certain parts of your application. Action filters are a powerful feature of ASP.Net MVC, allowing you to intercept and modify the execution of actions. By creating a custom action filter, you can dynamically add the Access-Control-Allow-Origin header based on the request’s origin or other criteria. This provides a flexible and secure way to manage CORS in your application.

Here are the steps to create and use a custom action filter:

  1. Create a new class that inherits from ActionFilterAttribute.
  2. Override the OnActionExecuting method.
  3. Inside the OnActionExecuting method, add the Access-Control-Allow-Origin header to the response.
  4. Apply the filter to the desired action or controller using the [YourFilterName] attribute.

Here’s an example of a custom action filter:

public class CorsAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", ""); filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type"); filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); base.OnActionExecuting(filterContext); } } 

To use this filter, simply add the [Cors] attribute to your controller or action. For example:

[Cors] public ActionResult MyAction() { // Your action logic here return View(); } 

This approach gives you fine-grained control, allowing you to enable CORS only where necessary. Remember to replace `` with specific origins in a production environment. You can also modify the filter to check the request’s origin and dynamically set the Access-Control-Allow-Origin header based on a whitelist of allowed origins. This adds an extra layer of security and prevents unauthorized access to your API.

Using the EnableCors Attribute from the Microsoft.AspNet.Cors Package

Another relatively simple method for setting Access-Control-Allow-Origin in ASP.Net MVC is by leveraging the EnableCorsAttribute, which is part of the Microsoft.AspNet.Cors NuGet package. This package provides a more structured way to configure CORS using attributes, making your code cleaner and more maintainable. The EnableCorsAttribute allows you to define allowed origins, headers, and methods directly in your controller or action, providing a convenient and declarative way to manage CORS. It eliminates the need to manually add headers in your code, simplifying the configuration process and reducing the risk of errors.

First, install the Microsoft.AspNet.Cors NuGet package. Then, you can use the EnableCorsAttribute like this:

using System.Web.Http; using System.Web.Http.Cors; [EnableCors(origins: "", headers: "", methods: "")] public class MyController : ApiController { public string Get() { return "Hello from the API!"; } } 

This example allows requests from any origin, with any headers, and any methods. Again, for production, you should replace the `` with specific values. You can also configure the EnableCorsAttribute globally in your WebApiConfig.cs file:

using System.Web.Http; using System.Web.Http.Cors; public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Enable CORS globally var cors = new EnableCorsAttribute("", "", ""); config.EnableCors(cors); // Other configuration settings } } 

This method offers a balance between simplicity and control. It’s easier to use than creating a custom action filter but still provides more flexibility than the Web.config approach. It’s important to carefully consider the allowed origins, headers, and methods to ensure the security of your application. You can also create custom CORS policies and apply them using the EnableCorsAttribute, allowing for more complex CORS configurations.

Security Considerations and Best Practices

While setting Access-Control-Allow-Origin in ASP.Net MVC, security should be your top priority. As discussed, using the wildcard character `` is generally discouraged in production environments. It’s much safer to explicitly list the allowed origins. This prevents unauthorized websites from accessing your API. Also, carefully consider the allowed headers and methods. Only allow the headers and methods that your API actually uses. This reduces the attack surface and makes your application more secure.

Here are some best practices to keep in mind:

  • Never use `` for Access-Control-Allow-Origin in production.
  • Explicitly list the allowed origins.
  • Only allow the necessary headers and methods.
  • Validate the origin of the request on the server-side.
  • Use HTTPS to encrypt communication between the client and server.

Failing to follow these best practices can lead to serious security vulnerabilities. For example, if you allow any origin to access your API, a malicious website could potentially steal sensitive data from your users. Similarly, if you allow unnecessary headers and methods, attackers could exploit these to launch attacks against your application. According to a recent report by Veracode, CORS misconfigurations are a leading cause of web application vulnerabilities [Veracode State of Software Security Report](https://www.veracode.com/state-software-security). Always test your CORS configuration thoroughly to ensure that it’s working as expected and that it’s not introducing any new security risks.

Consider also implementing other security measures, such as authentication and authorization, to protect your API. CORS is not a replacement for these measures, but rather a complementary security mechanism. By combining CORS with other security measures, you can create a robust and secure web application. Learn more about web security best practices.

Infographic illustrating CORS configuration options here.
FAQ: Common Questions About CORS in ASP.Net MVC -----------------------------------------------
What is the purpose of the `Access-Control-Allow-Origin` header?
The `Access-Control-Allow-Origin` header specifies the origin(s) that are allowed to access the resource. It's a crucial part of the CORS mechanism.
Is it safe to use `` for `Access-Control-Allow-Origin` in production?
No, it's generally not safe. It disables CORS protection and can open your application to security vulnerabilities.
How can I enable CORS for only specific actions in my ASP.Net MVC application?
You can use a custom action filter or the `EnableCorsAttribute` to apply CORS headers to specific actions or controllers.
What other headers are important for CORS?
Besides `Access-Control-Allow-Origin`, `Access-Control-Allow-Headers` and `Access-Control-Allow-Methods` are also important. They specify the allowed headers and methods for cross-origin **Question & Answer :** I have a simple actionmethod, that returns some json. It runs on ajax.example.com. I need to access this from another site someothersite.com.

If I try to call it, I get the expected…:

Origin http://someothersite.com is not allowed by Access-Control-Allow-Origin. 

I know of two ways to get around this: JSONP and creating a custom HttpHandler to set the header.

Is there no simpler way?

Is it not possible for a simple action to either define a list of allowed origins - or simple allow everyone? Maybe an action filter?

Optimal would be…:

return json(mydata, JsonBehaviour.IDontCareWhoAccessesMe); 

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*"); base.OnActionExecuting(filterContext); } } 

Tag your action:

[AllowCrossSiteJson] public ActionResult YourMethod() { return Json("Works better?"); } 

For ASP.NET Web API

using System; using System.Web.Http.Filters; public class AllowCrossSiteJsonAttribute : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Response != null) actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); base.OnActionExecuted(actionExecutedContext); } } 

Tag a whole API controller:

[AllowCrossSiteJson] public class ValuesController : ApiController { 

Or individual API calls:

[AllowCrossSiteJson] public IEnumerable<PartViewModel> Get() { ... } 

For Internet Explorer <= v9

IE <= 9 doesn’t support CORS. I’ve written a javascript that will automatically route those requests through a proxy. It’s all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code