Multiple CORS working for GET but not for PUT/POST with pre-flight requests Web api 2 - asp.net-web-api

When I configure CORS in my Web.config like following, every thing works:
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:3000"/>
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="accept, cache-control, credentials, content-type, authorization, origin, X-Requested-With, X-dev-mode"/>
</customHeaders>
However, when I try to enable multiple CORS like this:
// Filename: Global.asax.cs
protected override void Application_Start()
{
ApiConfig.Register(GlobalConfiguration.Configuration);
}
// Filename: ApiConfig.cs
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("http://localhost:3000,http://someOtherUrl.com/", "*", "*");
config.EnableCors(cors);
}
It works for GET (i.e. getting content, etc) but, when using POST/PUT (i.e. saving content, etc) it gives this error in browser (Chrome) console
Fetch API cannot load http://localhost:56214/api/1/content/SAVE. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The request is failing on OPTIONS. Please note that I do have custom handlers and my routes are also configured.
One more thing to mention is that the PUT/POST call to save content is an ajax call via react. Can that be an issue?

The problem is the trailing slash in your second URL. Change it to this and it works:
var cors = new EnableCorsAttribute("http://localhost:3000,http://someOtherUrl.com", "*", "*");

have you tried removing the blank space to the Access-Control-Allow-Methods like
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />

Related

Error facing on communication between asp.net webapi server and angular2 application

I am facing the CORS related issue when i try to connect my angular2 application and asp.net webapi application.
Error:-
register:1 Access to XMLHttpRequest at 'http://localhost:49457/api/UserDetails' from origin 'http://localhost:4200' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:4200, http://localhost:4200', but only one is allowed.
Here is my code for connecting for calling asp.net webapi url through my angular2 app:-
User.service.ts
GetUser(userobj:user):Observable<User>
{
return this.http.get<User>(`http://localhost:49457/api/UserDetails`,{responseType:"text"})
.subscribe(
function(response)
{
console.log("user details retreived successfully");
},
function(error)
{
console.log(error);
});
}
This is my code for asp.net webapi,
public class UserDetailsController : ApiController
{
private sampledbEntities dbentity = new sampledbEntities();
// GET api/<controller>
public IQueryable<Userdetail> GetUserdetails()
{
return dbentity.userdetails;
}
}
Actually when i run my asp.netwebapi server it is retrieving data correctly through browser.And also i have enabled
CORS in webapiconfig.cs,
void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
}
in web.config.cs,
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, X-Auth-Token" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
After enabling CORS in Webapiconfig.cs and web.config also i am facing the same error.
Please clarify how do i come out of this error,
Replace http://localhost:4200 with "*" from EnableCorsAttribute method.
void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(corsAttr);
}
and remove httpProtocol configuration settings from web.config.

No custom/authorization Headers in MVC 5 controller

I have an MVC 5 ViewController which does not accept headers from an Ajax call. The ajax call origin is a different website then the controller.
The Ajax call looks like:
window.jQuery.ajax({
url: 'http://localhost:54155/TestView',
headers: {'Authorization': 'token'},
cache: false,
contentType: 'application/json; charset=utf-8',
method: 'Get',
dataType: 'json',
data: {}
}).success(alert('succes?'))
.error(alert('failed'))
});
Cors is enabled on the controller side:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
And I'm trying to reach this controller:
public class TestViewController : Controller
{
public ActionResult Index()
{
var keys = Request.Headers.AllKeys;
return View();
}
}
If I send the request to a WebApi based on a WEP API 2 controller, the headers are ok. If I send a request with postman to the mvc controller the headers are ok as well.
The Headers contain the header Access-Control-Request-Headers, which has the value authorization. But Request.Headers["Authorization"] is null.
Custom headers like X-MyHeader turn up as value from Access-Control-Request-Headers, but when used like a key, they are all null.
Which part am I missing?
I had a same kind of issue - but this might resolve your problem
Install Microsoft.AspNet.WebApi.Cors from NuGet - Run this command
(Install-Package Microsoft.AspNet.WebApi.Cors) in your package
manager console - this will install your Cors
Remove your access allow origin code from your Web.config file
If it is Web Api add the below cod in your WebApiConfig.cs if not try to add in your Gloabl.asax
var cors = new EnableCorsAttribute("*", "*", "*", "*");
config.EnableCors(cors);
You will be wondering where that method EnableCors() will come using System.Web.Http.Cors; add this line in your using and see the magic
This might solve your problem - Finally its not a good idea to access your MVC controller from different domain try you use WebApi
If you want to access your MVC controller try out your ajax code form the same domain
Because WebApi is stateless but MVC is kind of session - Thanks happy coding !!

Web API 2 CORS IIS Express Debug and No Access-Control-Allow-Origin header

Empty web.api project, install Microsoft.aspnet.webapi.cors 5.2.3, add
config.EnableCors();
to webapiconfig. make controller and action
public class HomeController : ApiController
{
[EnableCors("*" , "*" , "*")]
public async Task<string> Get()
{
return await Task.FromResult("omg");
}
}
Debug app and Load up fiddler and do a request to http://localhost:61939/api/Home
there are no CORS headers present. web.config contains:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
what am I missing? Why would this not insert an Access-Control-Allow-Origin header in all request to my Get method?
Also the answer of defining CORS in web.config isn't an answer ... At some point I will need to add origin checking and potentially even checking the HTTP Method something like:
if(requestContext.HttpMethod == "POST" && (origin == "https://someplace.com" || origin == "http://localhost"))
What you've done is enough to enable CORS, you can also enable CORS on all the controllers using this code :
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
I'm not sure how you're testing it, but note that only once the request contains the Origin header, it returns the Access-Control-Allow-Origin header in reponse. If you omit the origin header in the request, the response wouldn't contain the Access-Control-Allow-Origin.

OPTIONS request returns "No 'Access-Control-Allow-Origin' header" error during ajax POST to a different domain

I'm struggling with CORS issue. I make a request from js to a different domain, the method allows cross domain request and all works fine with GET but not with POST request. Looks like OPTIONS method is called before the POST and return standard error
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
return Response.ok().entity(c).header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, x-xsrf-token, X-Requested-With, Accept, Expires, Last-Modified, Cache-Control").build();
On the client side I use angularjs
$http.post(url, data).success(...)
But also tried with
$.ajax({type:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}...})
the same result. what else can I do to fix POST request?
Add the below code to your Angular JS application config file
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

ExtJs 5 Ajax Request with ASP .NET

Despite my best efforts I am not able to send an Ajax request with Json data to a remote web server. I do not know what other places I can put enable CORS and am running out of ideas.
Azure Website App Settings:
cors:allowOrigins: *
MVC Controller: I had installed the NuGet Cors package
[EnableCors(origins: "*", headers: "*", methods: "*")]
Web.config:
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
ExtJs Ajax Request:
Ext.Ajax.request({
url: app.utilities.url,
defaultHeaders: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization,Content-Length, X-Requested-With'
},
cors: true,
useDefaultXhrHeader: false,
params: {
jsonData: Ext.util.JSON.encode(formData)
}
Yet I still get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at {my url} This can be fixed by moving the resource to the same domain or enabling CORS.
Is there something I am missing?
Would you consider JsonP (JSON with Padding)?
http://docs.sencha.com/extjs/6.0/6.0.0-classic/#!/api/Ext.data.JsonP
Only for the development purpose you can set below parameter in your browser.It works for me.
--disable-web-security --allow-file-access-from-files --allow-file-access

Resources