I have client and a server running on different ports. The server is running Web API 2 (v5.0.0-rc1).
I tried installing the Microsoft ASP.NET Web API Cross-Origin Support package and enabled it in WebApiConfig.cs. It gives me the EnableCors() function, so the package was installed correctly.
Here you can see my Register() function in WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
}
GET requests work fine. But when sending POST, I get the following:
OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159
OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159
XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.
According to Fiddler it only sends the OPTIONS request. It doesn't issue the POST afterwards.
So I'm guessing the config.EnableCors(cors); in the WebApiConfig.cs isn't doing anything, which leads to the server denying the client/browser to send a POST request.
Do you have any idea how to solve this problem?
EDIT 05.09.13
This has been fixed in 5.0.0-rtm-130905
CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors version 5.2.2. The following steps configured CORS like a charm for me:
Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" // run from Package manager console
In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS
GlobalConfiguration.Configure(WebApiConfig.Register);
In the WebApiConfig Register method, have the following code:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
}
In the web.config, the following handler must be the first one in the pipeline:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
In the controller derived from ApiController, add the EnableCorsAttribute:
[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController
That should set you up nicely!
I didn't need to install any package. Just a simple change in your WebAPI project's web.config is working great:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
Credit goes to: Using CORS in ASP.NET WebAPI Without Being a Rocket Scientist
For reference using the [EnableCors()] approach will not work if you intercept the Message Pipeline using a DelegatingHandler. In my case was checking for an Authorization header in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()] had no effect.
In the end found an example CrossDomainHandler class (credit to shaunxu for the Gist) which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.
public class CrossDomainHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
To use it add it to the list of registered message handlers
config.MessageHandlers.Add(new CrossDomainHandler());
Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions] IHttpActionResult method on the Controller.
I'm most definitely hitting this issue with attribute routing. The issue was fixed as of 5.0.0-rtm-130905. But still, you can try out the nightly builds which will most certainly have the fix.
To add nightlies to your NuGet package source, go to Tools -> Library Package Manager -> Package Manager Settings and add the following URL under Package Sources: http://myget.org/F/aspnetwebstacknightly
Make sure that you are accessing the WebAPI through HTTPS.
I also enabled cors in the WebApi.config.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
But my CORS request did not work until I used HTTPS urls.
Late reply for future reference. What was working for me was enabling it by nuget and then adding custom headers into web.config.
var cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);
This solved my issue:
in Web.config>>Inside system.webServer tags:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
And uncomment or delete this line inside system.webServer:
<remove name="OPTIONSVerbHandler"/>
Also, you need to declare enable cors either in webapiconfig.cs or in web.config. If you declare in both you may get an error something like :
'....origin 'www.example.com' blocked by cors policy due to multiple No 'Access-Control-Allow-Origin'('*','*').'
This did the trick for me.
To enable CORS,
1.Go to App_Start folder.
2.add the namespace 'using System.Web.Http.Cors';
3.Open the WebApiConfig.cs file and type the following in a static method.
config.EnableCors(new EnableCorsAttribute("https://localhost:44328",headers:"*", methods:"*"));
As far as I understood, the server got to have a header that specifies that Access from Origin is Allowed i.e. a request from the same server could be responded to.I used the following code :
// create a response object of your choice
var response = Request.CreateResponse(HttpStatusCode.OK);
//add the header
//replace the star with a specific name if you want to restrict access
response.Headers.Add("Access-Control-Allow-Origin", "*");
//now you could send the response and it should work...
return response;
Below code worked for me,
App_Start -> WebApiConfig
EnableCorsAttribute cors = new EnableCorsAttribute("\*", "\*", "GET,HEAD,POST");
config.EnableCors(cors);
Related
Briefing
I am aware what CORS is, and how it works.
Lately, I performed a big update on my application.
Since then, my Client Application cannot connect to the backend due to the CORS error.
My Admin Application has no problems connecting to the BE.
I compared the web.configs and a couple of other files, and cannot see much of a difference in the Client configuration.
(Admin: FE=MVC5/ASP | BE= ASP.NET)
(Client: FE= Angular 8.1 | BE= ASP.NET)
Changelog of what happened in the update:
Implemented Unity Dependency Injection for the Web Controllers
Made all the WebControllers inherit from a BaseController that handles the DI
Updated a couple of Microsoft.AspNet "Web" Nugets from v5.2.3 -> 5.2.7
Cors has worked without any issue before this. I looked at my file changes in my git client and could not find any changes to files that could relate to this CORS issue at first glance.
If you need more information or more insight into specific files, let me know in the comments and I will provide them.
Code Snippets
Config-based CORS configuration is commented out (by a previous developer) in Web.Config:
<httpProtocol>
<customHeaders>
<!--<add name="Access-Control-Allow-Methods" value="GET, POST" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token" />
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Credentials" value="true" />-->
</customHeaders>
</httpProtocol>
When I uncomment this, and change the origin to my server,
the "No-Access-Control-Origin" error disappers, but I get error 500 (Internal Server Error) instead.
CORS is configured via the WebApiConfig, this class gets executed and loaded, I checked that with a breakpoint. I tried both new EnableCorsAttribute("subdomain.ourdomain.com",... and new EnableCorsAttribute("*",... ...To no avail.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Obviously I have googled, and found the Enable-Cors.org for ASP.NET, which all looks really good.
I have checked my WebApiConfig against what is described as the global CORS approach on that page, and to me it looks like that my WebApiConfig.cs is configured correctly.
I am a little stuck here.
I think that your problem is that you have not applied the Attribute to your controllers as per the guidance in microsoft docs
For the global solution, you need to go with the ICorsPolicyProviderFactory
Create first your own Wrapper around the attribute:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class MyCorsPolicyAttribute : Attribute, ICorsPolicyProvider
{
private CorsPolicy _policy;
public MyCorsPolicyAttribute()
{
// Create a CORS policy.
_policy = new CorsPolicy
{
AllowAnyMethod = true,
AllowAnyHeader = true
};
// Add allowed origins.
_policy.Origins.Add("your.domain1");
_policy.Origins.Add("your.domain2");
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request)
{
return Task.FromResult(_policy);
}
}
Then create the factory provider:
public class CorsPolicyFactory : ICorsPolicyProviderFactory
{
ICorsPolicyProvider _provider = new MyCorsPolicyProvider();
public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
{
return _provider;
}
}
And last but not least register it in your settings
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SetCorsPolicyProviderFactory(new CorsPolicyFactory());
config.EnableCors();
// ...
}
}
Let me know how this works for you.
It turned out that CORS was just fine (a couple slight adjustments, rebuilds and redeploys did the trick)
But the main culprit (Error 500) was coming from missing assemblies, that Visual Studio 2019's WebDeploy did not correctly move to the server.
Manually copying the files over to the server fixed everything.
For reference I'm using Visual Studio 2017 and Windows 10.
I have an MVC webapi project designed using a template provided by Visual Studio with accounts that are stored in an SQL database. I have another project which is the website itself that the users log into. I'm attempting to debug in VS but am being met with an access is denied error message whenever a GET request is made outside of the initial login. I've enabled CORS on the webapi but it didn't seem to make much of a difference.
Here's how I enabled CORS.
In the WebAPIConfig file I have the following:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And then in the Web.config file I have this:
<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>
This is the code from the website making the call:
function getProfilePicture(username){
var returnValue = [];
jQuery.support.cors = true;
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'http://localhost:60690/api/ProfilePicture?Username=' + username, false);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'));
xmlhttp.send();
if (xmlhttp.status == 200) {
returnValue = jQuery.parseJSON(xmlhttp.responseText);
}
}
return returnValue;
}
The error message says "SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied."
Did I not properly enable CORS?
Update
I downloaded Postman in an attempt to figure out the issue. I'm actually able to make GET calls with Postman without any errors. It's returning the data and everything. One thing I did notice is it doesn't look like the Authorization header is actually being sent. It's missing from the data in Fiddler.
Specifying Access-Control-Allow-Credentials: true as a response header is incompatible with Access-Control-Allow-Origin: *. If you're going to use credentials, you must use Access-Control-Allow-Origin: <value-of-origin-request-header>.
I am trying to add some [WebMethod] annotated endpoint functions to a Webforms style web app (.aspx and .asmx).
I'd like to annotate those endpoints with [EnableCors] and thereby get all the good ajax-preflight functionality.
VS2013 accepts the annotation, but still the endpoints don't play nice with CORS. (They work fine when used same-origin but not cross-origin).
I can't even get them to function cross-origin with the down and dirty
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
approach -- my browsers reject the responses, and the cross-origin response headers don't appear.
How can I get CORS functionality in these [WebMethod] endpoints?
I recommend double-checking you have performed all steps on this page: CORS on ASP.NET
In addition to:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Also try:
Response.AppendHeader("Access-Control-Allow-Methods","*");
Try adding directly in web config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
Failing that, you need to ensure you have control over both domains.
FYI, enable CORS in classic webform. In Global.asax
void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.EnableCors();
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
If you need the preflight request, e.g. so you can send authenticated requests, you are not able to set Access-Control-Allow-Origin: *. It must be a specific Origin domain.
Also you must set the Access-Control-Allow-Methods and Access-Control-Allow-Headers response headers, if you are using anything besides the defaults.
(Note these constraints are just how CORS itself works - this is how it is defined.)
So, it's not enough to just throw on the [EnableCors] attribute, you have to set values to the parameters:
[EnableCors(origins: "https://www.olliejones.com", headers: "X-Custom-Header", methods: "PUT", SupportsCredentials = true)]
Or if you want to do things manually and explicitly:
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "https://www.olliejones.com");
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", "X-Custom-Header");
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Methods", "PUT");
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
One last thing - you do have to call .EnableCors() on initiation. In e.g. MVC or WebAPI, you would call this on HttpConfiguration, when registering the config and such - however I have no idea how it works with WebForms.
If you use the AppendHeader method to send cache-specific headers and at the same time use the cache object model (Cache) to set cache policy, HTTP response headers that pertain to caching might be deleted when the cache object model is used. This behavior enables ASP.NET to maintain the most restrictive settings. For example, consider a page that includes user controls. If those controls have conflicting cache policies, the most restrictive cache policy will be used. If one user control sets the header "Cache-Control: Public" and another user control sets the more restrictive header "Cache-Control: Private" via calls to SetCacheability, then the "Cache-Control: Private" header will be sent with the response.
You can create a httpProtocol in web config for customHeaders.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" values="*" />
</customHeaders>
<httpProtocol>
I think your code looks good, but IIS does not send the header entity alone with response expectedly. Please check whether IIS is configured properly.
Configuring IIS6
Configuring IIS7
If CORS doesn't work for your particularity problem, maybe jsonp is another possible way.
For the web form, you can use
Response.AddHeader("Access-Control-Allow-Origin", "*");
instead of
Response.AppendHeader("Access-Control-Allow-Origin", "*");
The first one works for old version of ASP.Net Web Form.
You can do like this in MVC
[EnableCors(origins: "*", headers: "*", methods: "*")]
public ActionResult test()
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
return View();
}
I have three applications in my architecture.
They are on the same server but having different port numbers.
A - Token Application (port 4444) - Asp.net WebApi
B - API Application (port 3333) - Asp.net WebApi
C - UI Application (port 2222) - AngularJS App.
The application flow is like below
1- The UI project gets the token from Token Application (It requires Windows Auth.)
Ex : awxrsdsaWeffs12da
2- UI application puts this token to a custom header which is named as "accessToken"
Ex : accessToken : awxrsdsaWeffs12da
3- UI application sends a request to API Application
Ex: http:myaddress:3333/api/TheRestServiceHere
UI application gets 401 Error.
Which sends OPTIONS method. (I guess preflight issue)
In my web api project I enabled Cors like this below.
public static void Register(HttpConfiguration config)
{
....
//CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
....
}
Config
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
json.SerializerSettings.Formatting = Formatting.None;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
So I am looking for a solution to call API application (B) controllers
and get 200 :)
Regards
I fixed this in an application I am working on by creating a module that responds to requests that are using the OPTIONS verb. You should probably modify it a bit to include the verbs and content type that the application is requesting. In my case, I decided to post everything as JSON (which requires the pre-flight check). The module is as follows:
public class OptionsModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, args) =>
{
var app = (HttpApplication) sender;
if (app.Request.HttpMethod == "OPTIONS")
{
app.Response.StatusCode = 200;
app.Response.AddHeader("Access-Control-Allow-Headers", "content-type");
app.Response.AddHeader("Access-Control-Allow-Origin", APISettings.ApplicationOrigin);
app.Response.AddHeader("Access-Control-Allow-Credentials", "true");
app.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
app.Response.AddHeader("Content-Type", "application/json");
app.Response.End();
}
};
}
public void Dispose()
{
}
}
Then you need to register it in your web.config:
<system.webServer>
<modules>
<add name="HandleOptions" type="namespace.OptionsModule" />
</modules>
</system.webServer>
Another thing you may want to do is specify the allowed origin explicitly. Chrome doesn't like having a wildcard there.
One of my friend solved the issue by using OPTIONSVerbHandler.
When UI application wants to use GET method, browser sends
OPTION method first to the server (Preflight). Then if Preflight request is OK it sends GET request.
For CORS test purpose we used the following code to send GET method.
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
var adress = "http://10.10.27.36:3434/backend/api/role";
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'accessToken': 'some value',
'Origin' : ''
}
});
$.ajax({
type: "GET",
url: adress,
dataType: "json"
});
});
</script></head><body></body></html>
To handle OPTION method which sends by browser before GET you should have the following settings.
1- Webconfig
<system.webServer>
<handlers>
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" resourceType="Unspecified" requireAccess="None" />
</handlers>
</system.webServer>
2- Adding OPTIONSVerbHandler with following settings
Click on request restrictions
3- Our Header Settings we have accessToken which is custom as you can see
This problem happened for Cordova v11, platform for Android. I used the solution provided by Jereme (the top rated answer) with one exception: In OptionsModule, I had to omit the statement
app.Response.AddHeader("Access-Control-Allow-Origin", APISettings.ApplicationOrigin);
Instead in the web.config file I added in the <system.webServer> section the following:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<!-- Note: "localhost" for Cordova is not valid, only * worked. -->
</customHeaders>
</httpProtocol>
A word about Cordova in case one is unfamiliar. Cordova packages a native app for the Android platform with a “javascript page” included in the app, using a web view in the app to display the page. Using the Chrome debugger to view the javascript page, the page origin appears as localhost. However, localhost is not an acceptable value for the Access-Control-Allow-Origin header; therefore I had to use “*” in the Web.config file. When I had the response header in the OptionsModule, the preflight response was ok (status 200), but not the response for the XMLHttpRequest (the api) that initiated the preflight request. Putting the custom header only in the Web.config file allowed both responses to be ok (status 200).
For Azure Environment
You need allow origins from the portal.
Is it possible to implement "Access-Control-Allow-Origin" header in asp.net
From enable-cors.org:
CORS on ASP.NET
If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
See also: Configuring IIS6 / IIS7
Another option is to add it on the web.config directly:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://www.yourSite.com" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
...
I found this in here
1.Install-Package Microsoft.AspNet.WebApi.Cors
2 . Add this code in WebApiConfig.cs.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
3. Add this
using System.Web.Http.Cors;
4. Add this code in Api Controller (HomeController.cs)
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
[HttpGet]
[Route("api/Home/test")]
public string test()
{
return "";
}
}
You would need an HTTP module that looked at the requested resource and if it was a css or js, it would tack on the Access-Control-Allow-Origin header with the requestors URL, unless you want it wide open with '*'.
Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.
Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:
{
"/api": {
"target": "http://localhost:49389",
"secure": true,
"pathRewrite": {
"^/api": "/api"
},
"changeOrigin": true
}
}
Put the file in the same directory the package.json then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from the app component is as follows:
return this.http.get('/api/customers').map((res: Response) => res.json());
Lastly to run use npm start or ng serve --proxy-config proxy.conf.json