I have a .Net WebApi project (NOT .Net Core, PLEASE DO NOT USE .Net Core ANSWER). and i need set more origin site, first, i tried one origin for testing, but not work. (nuget: Microsoft.AspNet.Cors and Micorsoft.AspNet.WebApi.Cors, version 5.3.0)
These steps from Microsoft and Stackoverflow, and I followed to use:
Step1: Set Origin/Headers/Methods from EnableCorsAttribute globally.
Step2: Remove Web.Config system.webServer setting. (“Allow-xxxxxx” here, so I removed it.)
Step3: Client is Angular that send a request to server, and method is POST for testing.
Browser shows:
There is no origin domain in Server response, and the header is different from EnableCORS setting.
I set origin “http://localhost:4200”, method is “GET,POST,PUT,DELETE,OPTIONS” in WebApiConfig.cs for globally, Chrome show the server Response no Origin, and method is “OPTIONS, TRACE, GET, HEAD, POST”.
I need enableCORS with multiple domains and credentials, so I can’t add Header from Application_BeginRequest, because it is not support multiple domains.
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
//Response.Headers.Add("Access-Control-Allow-Origin", ConfigurationManager.AppSettings["AllowAccessDomain"]);
Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200,http://localhost:4300");
}
}
It gets CORS, not allow origin error.
My code about EnableCORS:
WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API
//config.EnableCors();
EnableCorsAttribute enableCorsAttribute = new EnableCorsAttribute(
"http://localhost:4200",
"Origin,X-Requested-With,Content-Type,Accept,Authorization,Set-Cookie,CaptchaToken",
"GET,POST,PUT,DELETE,OPTIONS"
)
{
SupportsCredentials = true
};
config.EnableCors(enableCorsAttribute);
// Web API Route
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Global.asax.cs:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Web.config
1. Remove tag: <system.webServer>
2. Remove <system.webServer> contain, only tag.
Same of message from 1 or 2, CORS error.
Chrome Browser Message:
Access to XMLHttpRequest at ‘http://localhost:9600/api/server’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
What can I do more for this?