Unable to make HTTP post request to .NET Core MVC - asp.net-core

I'm currently working on a project where I'm using ASP.NET Core MVC (views are running on another port using Vue). I have set up my models and controller set up and I've tested these using swagger. They work exactly as expected. I have tested the post method on swagger and it works, but requests from my view on another port running Vue and Postman return a 405 error. Inspecting the response headers on Postman, I can see "Allow : DELETE, GET, PUT". Because my view will be running on another port, I've already added CORS the following to my startup configure method (not currently concerned about security implications):
app.UseCors(builder => {
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
My controller features the following for the POST method:
[ResponseType(typeof (Review))]
[HttpPost]
public async Task Post(Review review)
{
db.Reviews.Add(review);
await db.SaveChangesAsync();
}
I am accessing the URL on Postman from https://localhost:44334/reviews/Post. Reviews being the controller and post is the method. I am not receiving any cross original control errors, just this 405. Why might it be doing this and how can I debug this?
I was trying to post to https://localhost:44334/reviews/Post but my router was not set up like this. Changing the URL to https://localhost:44334/reviews/ and setting the method to Post worked and returned a success 200 response.

It is very common issue. For requests coming from localhost AllowAnyOrigin() doesn't work. You need to allow the origin explicitly like:
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader();
}));
In the configure method tell CORS to use the policy you just created:
app.UseCors("ApiCorsPolicy");
Requests from postman passes the CORS because they attach special headers.

Related

Angular with OData batch request fails on IIS

I am using Odata with .Net Core web api. For client side i am usin angular 13. OData batch request works fine in localhost. After published on iis with 'ng-build' i am getting a cors error from odata batch request. I already allow origins. What am i missing?
I am not sure but think it was really related with cors.
I only added this code block in to "Configure" method in startup.cs and problem solved.
app.Use((context, next) => {
context.Response.Headers["Access-Control-Allow-Origin"] = "*";
return next.Invoke();
});
But before the batch, i didn't need this code block i have added. All request works fine (except batch) without the code block i have added. I am trying to understand this part.

Laravel Access to XMLHttpRequest error how to fix

I have a Laravel 7 application and I'm trying to access an external URL in a Bootstrap model window. When I use the below jQuery function, on button click, I want to load the model and show the external website.
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
I get the bellow error.
Access to XMLHttpRequest at 'http://****' from origin 'http://****'
has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: Redirect is
not allowed for a preflight request.
I have searched and found one solution to use middleware. I created the middleware file in app\http\Middleware\Cors.php.
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',
'Accept,Authorization,Content-Type');
}
After that I have added the following in app\http\Kernel.php.
protected $middleware = [
....
...
\App\Http\Middleware\Cors::class,
];
But I still get the same error. How can I fix this error?
Laravel 7 has been released in March and provides built-in support for CORS so developers don't need to use third-party packages to enable CORS in their Laravel apps.
You can use config/cors.php file for your cors settings.
For more details please follow the link - https://www.techiediaries.com/laravel/laravel-7-6-cors-example-and-tutorial/
Since you didn't explicitly mention it I'll assume you didn't do this:
you have to enable CORS for every route you want to use it with.
According to:
https://github.com/fruitcake/laravel-cors
There can be CORS on Both side on
1 API side at external URL. ( this you cannot change)
2 At your bootstrap Laravel application.( this you can change)
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
This is just a Jquery code. Can you convert this code to some server side language like php?
Remember CORS can be overridden by server side code.

Vue JS axios HTTP500 Internal Server

I have create an Asp.Net Core Web API and have checked it is working correctly using postman.
I have downloaded the GitHub Project from this blog: https://paweljw.github.io/2017/09/vue.js-front-end-app-part-3-authentication/
I have modified the url in src/backend/vue-axios/axios.js to my web api url
No matter what I do all I get is:
HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.
(XHR)OPTIONS - http://localhost:61783/api/token
I have put a break point on the Web API Token method and it is never hit.
Any ideas on how to fix this?
Finally cracked it, it was CORS all along!
services.AddCors(options =>
{
options.AddPolicy("AllowAllHeaders",
corsbuilder =>
{
corsbuilder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:8080");
});
});
The WithOrigins helped
And enabled cors with a policy on the controller
[EnableCors("AllowAllHeaders")]

CORS policy blocking POST requests to API

I'm trying to deploy an app I created online. The UI is created using vue.js and it's calling a API written in dotnet core. I'm running dotnet core 2.2.
The web project and the API are on different servers and accessible under different domains, the web project is hosted on Netlify if that makes a difference. I managed to set up the CORS policy so that locally everything worked fine. When I access the app on the webserver I receive CORS errors whenever I post data. My GET and DELETE requests work just fine.
Here is my CORS policy
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("Default", builder =>
{
builder.WithOrigins(/* the domain where my web project is hosted */);
builder.AllowAnyMethod();
builder.AllowAnyHeader();
builder.AllowCredentials();
});
});
}
So I'm thinking everything should be fine. AllowCredentials is required because I'm using SignalR which otherwise wouldn't work.
The error message in the dev tools is
POST [my api endpoint] 400 (Bad Request)
Access to XMLHttpRequest at '[my api endpoint]' from origin 'https://xxx.netlify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And when I look into the console where my dotnet project is running I see the following error message
Connection id "0HLQNTR19GE1T" bad request data: "Requests with 'Connection: Upgrade' cannot have content in the request body."
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Requests with 'Connection: Upgrade' cannot have content in the request body.
at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1MessageBody.For(HttpVersion httpVersion, HttpRequestHeaders headers, Http1Connection context)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1Connection.CreateMessageBody()
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication`1 application)
So far I tried setting the Access-Control-Allow-Origin = "*" Header via the netlify.toml file, using the [EnableCors] attribute on my controller action. I edited my AJAX request (axios) and set withCredentials: true and in general played around with the CORS policy a lot. Unfortunately without luck and I'm running out of ideas.
I'm happy about any suggestions.
Check your nginx.conf file for a line called proxy_set_header and set it to Connection $http_connection

ionic yii2 Response for preflight has invalid HTTP status code 500

I have a Ionic App and I'm trying to do a POST:
$http({
url: url+'/usuario/log',
method: 'POST',
data: {usuario : $scope.data.usuario, senha:$scope.data.senha},
headers : {'content-type':'application/json; charset=UTF-8'}
}).then(function(result) { ... });
On the server side I have a Yii2 application:
public function actionLog(){
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: *");
header("Access-Control-Allow-Headers: content-type");
$params = json_decode(file_get_contents('php://input'),true);
$usuario = $params['usuario'];
$senha = $params['senha'];
...
}
But the error I got is always this, I send a POST and get a OPTIONS
OPTIONS http://www.nexusolucoes.com.br/personal/web/usuario/log
XMLHttpRequest cannot load http://www.nexusolucoes.com.br/personal/web/usuario/log. Response for preflight has invalid HTTP status code 500
The problem seems to be related with CORS, if the backend is on a different domain than the frontend the browser will always send an OPTIONS request first, to confirm that the cross domain sharing is allowed for the frontend domain.
If the browser gets a proper response for the OPTIONS, then, the POST request (the one you want) will be triggered as usual.
To sum up, you need to: Add a mapping on the URL Manager to respond to the OPTIONS verb for the exact same URL where you're sending the POST. Then, you need to create an action within a controller or to use the Yii's yii\rest\OptionsAction along with the CORS filters to allow the frontend domain to make the POST request.
Please check the following links for more information:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
http://www.yiiframework.com/doc-2.0/yii-filters-cors.html
http://www.yiiframework.com/doc-2.0/guide-rest-controllers.html