I'm developing a web application based on an Angular 6 client and ASP.NET Core WebAPI for web services.
At the moment (initial development phase) i have a simple architecture that consists of two web services, one that manages authentication and identities, the other one that holds the applicative logic (business logic, updating db, ecc.).
I'm using JWT Bearer token for client authentication.
Everything works fine with my authentication service, but when I try to call the application service I obtain this error in the Chrome browser console:
Failed to load http://localhost:59207/api/Files/Upload: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.
This error is preceded by another one:
POST http://localhost:59207/api/Files/Upload 500 (Internal Server Error)
Is, in some way, the second error I get related to the Internal Server Error it is preceded by?
I test my POST call from Postman and everything works fine, no server-side errors and the data i want back from my service is returned.
I already put in place everything I know about CORS in ASP.NET Core.
Startup class method named "ConfigureServices" contains, as first row:
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Then this is called in the "Configure" method:
app.UseCors("AllowAll");
Also I put the EnableCors Attribute on every controller class like this:
[EnableCors("AllowAll")]
Anyone has an idea of how I can get out of this mess?
From what I get, this is how CORS is intended to be used and I already got it running this way on other projects (but never with ASP.NET Core 2).
Thank you in advance
This may not be an answer to your situation, but I've run into this issue quite often in the past. It's a Chrome issue when talking between two localhosts upon POST requests.
Try using another browser and see if it works; if so, you can continue using Chrome by disabling Security
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
hope this helps.
Related
Trying to provide more info and not sure how much is relevant.
One of our webapi is deployed to IIS : abcdomain.com/xyzweb. We started upgrading our env to .net 7 from .net 5. Web api also uses ServiceStack 6.4.
One of the route defined in the c# Webapi, ServiceStack plugin is "/api". Until recently requests to endpoint abcdomain.com/xyzweb/api was fine. But now (.net 7 upgrade?) we noticed that the calls to endpoint does not reach the (http get/post method) handler. We have a small middleware defined in startup.cs configure method and see the execution flow through the middleware code when the abcdomain.com/xyzweb/api request is made and the middleware ends by calling next() and after which execution flow lost (webapi is still live).
After much trials, something I read but could not put my fingers on the content, went ahead and changed the route definition to "/apihello" instead of "/api" and then the requests started working as before.
Any pointers what made it break or what made it work?
Searching is difficult with "api", brings only irrelevant results.
I would like to add that before changing /api to /apihello, the http request would return HTTP status 200 (though it did not go to the handler) and Raw response "Error: System.NotImplementedException: The operation '' does not exist for this service".
You can disable (or change) ServiceStack's JSON /api pre-defined route with:
ConfigurePlugin<PredefinedRoutesFeature>(feature => feature.JsonApiRoute = null);
I have a React frontend connecting to a .NET CORE WebAPI, I'm able to call, GET, Delete, and Create in one controller with no issues, however, on another controller, when I call the Create I get the CORS policy error message. What would cause the error in one controller and only the Create? I can call the Get and Delete with no issues, I can also call the Create from PostMan with no issues, just when I call it from my React App.
Create Code: (this works when I test it from Postman, I'm connecting to the API on my Local host for the time being, and only this one controller in the WebAPI is kicking me out the CORS policy error and only on the Create Call)
public IActionResult Create(CarDetails, details)
{
db.CarDetails.Add(details);
db.SaveChanges();
return Ok(details.DetailsId);
}
PostMan ignores CORS headers and will just not care about them. That is a reason for PostMan working while the browser does care.
With that said I do no really know why your API stops one request and not the other. Are there differences in the headers?
I think your problem would have a higher chance of getting solved when asked in a .NET forum. CORS errors are caused by settings for your backend/api host and not caused by React/JS/Client side code.
You might need to allow more headers, open up localhost:3000 or some other setting.
I got it working. once I added this to my API call file, it worked:
headers: {
"Content-type": "application/json"
}
The Problem
Sending an http request to an ASP.NET Core API server (although I believe this will apply to a variety of different .NET style servers) I get the CORS error: MethodDisallowedByPreflightResponse. I specifically am getting this error on a PUT request (it does not occur on POST or GET requests).
What I tried:
Googling, no one else has written about this specific error.
DevTools Network tab (ie. inspecting the actual Http request headers and content)... There is nothing in the preflight request/response that seems to indicate anything about which methods are allowed and which aren't.
My Answer:
Looking at my server's CORS settings, I realized that the .AllowAnyHeader() method on the Cors middleware might indicate there is a similar method for allowing any Methods. I was correct.
Use .AllowAnyMethod() to fix this error (assuming you actually want to allow any http method type).
Here is where you specifically put this on your server (I'm using ASP.NET CORE API, version 5 I believe) :
//Startup.cs
//.... in the "Startup" class "ConfigureServices" method....
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("https://example.com")
.AllowAnyHeader()
.AllowAnyMethod(); //THIS LINE RIGHT HERE IS WHAT YOU NEED
});
});
// ... the rest of your code, other middleware, etc.
This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500
I have published Web API project on IIS with all configurations.
Already tried things:
.Net Core hosting bundle. (added)
and I can see it in IIS target website modules.
IIS settings checked many times.
Note:
API URL is just returning a method which have string return type which is
But when I hit another method which have list return type it shows the message "localhost is currently unable to handle this request".
Without publishing project on IIS it is working perfectly fine.
Default methods controller are working perfectly fine which returns string.
But when I call other methods in the controller it shows error message "Localhost is currently unable to handle the request"
*URL not working (calling default method which returns string)
working URL (calling another method in controller)
1- enable app.UseDeveloperExceptionPage(); in startup.cs file.
Now execption will show in broweser instead of "Localhost is currently unable to handle the request"
Issue was with the connection string after adding userid and password in connection string my issue resolved.
Thanks for your help and guidance.
Make sure this part comes on top in your Configure method in Startup file
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "learning_todo_jwt v1"));
}
If the error code you get is just 500, not 500.x, then this describes what's going on:
The app starts, but an error prevents the server from fulfilling the request.
This error occurs within the app's code during startup or while creating a response. The response may contain no content, or the response may appear as a 500 Internal Server Error in the browser. The Application Event Log usually states that the app started normally. From the server's perspective, that's correct. The app did start, but it can't generate a valid response. Run the app at a command prompt on the server or enable the ASP.NET Core Module stdout log to troubleshoot the problem.
So you need to figure out what went wrong in your app.
There are more troubleshooting steps under the Troubleshoot on IIS section. In my experience, the most useful troubleshooting step is enabling the stdout log in web.config.
<aspNetCore processPath="bin\myapp.exe" stdoutLogEnabled="true" stdoutLogFile=".\stdout" />
That should hopefully show you an error message in that file and you can search for that error.
I'm currently creating an MVC 6 project (beta 8) which includes some APIs. Along with this is an accompanying Word App which talks to these APIs (just GET methods at present), however all my ajax get JSON requests from the Word app result in an 'Error: Access is denied.' message.
After much searching I believe this may be a CORS issue, so I have enabled this in my startup.cs by adding the following into ConfigureServices:
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());
});
and then
app.UseCors("AllowAllOrigins");
into Configure, but this makes no difference, I still just receive the access denied message. I've attempted adjusting my CORS options to allow all methods and tried various other options, including adding
[EnableCors("AllowAllOrigins")]
on the actions, but again it makes no difference.
I am running both projects locally and manually navigating to the api via a browser returns the results without a problem, as does my swashbuckler setup.
Am I missing something obvious here?
In my experience, some browsers don't allow the wildcard response for allow origin when over an SSL connection (which is what you get when you use AllowAllOrigins). If you need your traffic to go over SSL, you need to respond with a list of allowed origins instead of the wildcard.
This answer has a good approach.