WebAPI CORS Policy when Creating new record - c#

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"
}

Related

.Net 7 ServiceStack 6.4 breaking api route that has just "/api"

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);

How to reject requests in a .NET Core API based on the values sent in the Accept header?

Reading about how to return status code 406 in a .NET Core API for requests that require a response in a format not supported by my API, I found that I need to set the following option in the AddMvcCore method:
services.AddMvcCore(options =>
{
options.ReturnHttpNotAcceptable = true;
});
However, I noticed that even if a client requests for an unsupported format, the request is forwarded to the endpoint and only after processing done in Controller that the status code 406 is returned.
I would like to know if .NET Core has a ready-made solution that blocks the request, that is, returns the status code 406 without having to execute the endpoint code. I have found solutions in which Middleware can be written to perform such a task, but I would really like to know if there is an alternative built into the framework itself.

Overriden HandleAuthenticateAsync method in AuthenticationHandler in ASP.Net Core Web Api is called twice with different headers

I have one application that sends a GET request to another application.
This request is generated once, and sent once. I have validated this by generating a System.Net.HttpWebRequest object, populating it, and debugging my workflow until I call request.GetResponse(). This is only called once.
In the application that recieves the request, I have overriden the AuthenticationHandler's HandleAuthenticateAsync method with some custom authentication logic. When I debug the request, my validation works, and I return a valid AuthenticateResult. However, immediately after this returned, my app goes into the HandleAuthenticateAsync a second time. This time the request is missing the Authentication header, and the app therefore returns a 401 response.
Does anyone have any clue what might be wrong here?
Found it. The answer for me was to remove app.UseHttpsRedirection(); from Startup.cs' Configure method, since I was calling this application through http://localhost for testing purposes.

ASP.NET Core 2 CORS not enabled

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.

Move ASP.NET WebApi 2.0 controller to separate application

We have a WebApi 2.0 application with several controllers, one of which is used to relay data. Due to issues with scalability, we want to move that particular controller out to a separate process so that we can scale it separately from the rest of the application, possibly on a different server altogether. We don't want to break compatibility though, and until we can get all of the clients updated, we will still have requests being made to the old endpoint that controller sat on. What is the simplest way to redirect those requests (it must work with GET/POST/DELETE) to the new location? Does this have to be done within IIS, or is there a way to modify the route? So far we've tried simply returning a redirect response within the old controller, but this doesn't work properly for POST:
public async Task<HttpResponseMessage> Post()
{
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://new/api/endpoint");
return response;
Even if it did, we have some library components that use WebClient with auto-redirect turned off, and those would need to be refactored, which is not ideal. Is there a guaranteed solution?
A redirect is nothing more than an HTTP response with a particular status code and some extra information. If your client application isn't going to follow a redirect than that's not an option for solving your problem.
You could have your Post() method act as a proxy for the other web service. As an example, if your first API is at example.com/Site1 and your second API is at example.com/Site2 then you could have your client make a request to Site1 while Site1 internally makes a request to Site2.

Categories

Resources