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", "*");
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
© 2022 - 2024 — McMap. All rights reserved.