Hi I have developed one small web api crud application and hosted in IIS server. I am able to do the all the operations. I hosted in the server 192.168.0.213:7777 and it is working fine. These services i am trying to access from another application through angularjs as below.
this.deleteSubscriber = function (user_id) {
var url = 'http://192.168.0.213:7777/api/User_Creation/' + user_id;
return $http.delete(url).then(function (response) {
return response.data;
});
}
Whenever i tried to delete user i am getting error message as below.
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
XMLHttpRequest cannot load http://192.168.0.213:7777/api/User_Creation/37. 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:26079' is therefore not allowed access. The response had HTTP status code 405.
May i know why I am getting this issue? Do i need to make any changes in the iis or in my application? Thank you...
You can enable CORS in iis8 by configuring customHeaders
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="POST,GET,DELETE"/>
</customHeaders>
</httpProtocol>
</system.webServer>
Can also be configured at code level - Enabling Cross-Origin Requests in ASP.NET Web API 2
Related
I am getting below CORS errors for PUT and DELETE request only, GET and POST requests are working fine:
Access to XMLHttpRequest at 'https://localhost:444/api/...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Background about my application: frontend is in React(next.js) and backend is in .NET 5. In backend project, I have already set the CORS policy to allow any header, method and specific origin but still now working. When I run the API project on IIS Express, it works but when I deployed it to IIS, it failed with above error.
Here are the CORS policy in .NET 5 project:
-- public void ConfigureServices(IServiceCollection services)
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:3000");
});
-- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseRouting();
app.UseCors();
app.UseAuthorization();
Here is the OPTIONS request for PUT:
**General:**
Request Method: OPTIONS
Status Code: 204
Remote Address: [::1]:444
Referrer Policy: strict-origin-when-cross-origin
**Response Headers:**
access-control-allow-headers: content-type
access-control-allow-methods: PUT
access-control-allow-origin: *
date: Fri, 24 Sep 2021 01:49:11 GMT
server: Microsoft-IIS/10.0
x-powered-by: ASP.NET
Any idea?
The problem is not with the CORS policy but the WebDAVModule in the web.config. If you try the PUT or DELETE request from browser or Postman, you'll get the 405 Not allowed error from the web server.
I have tried the same from the React app. I got the following response.
The console shows from origin 'http://localhost:9100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource., but the Network tab shows the error's status code is 405.
To fix this, you have to add the following configs in web.config.
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,PUT,DELETE,DEBUG" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
</handlers>
Even I have removed the port number from Startup class and added the following for CORS.
// global cors policy
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials()
);
Please refer the .Net core application here and React app sandbox here.
Read more about the 405 method not allower error here
I guess your problem is WebDAVModule is disabling PUT and DELETE methods. You must have below code block inside <system.webServer> in your web.config file just before <handlers> as below:
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
</handlers>
I believe when you deploy your code the client url will change from
http://localhost:3000 to say [http://example.com/8080][1]
Put this url in WithOrigins method -
-- public void ConfigureServices(IServiceCollection services)
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
***.WithOrigins("http://example.com/8080");***
});
first you need to change the port you is using port 444 is reserved, by combention you need to start at port 3000, the first 2000 ports might be used by the OS. port 444 is free to use if
wikipedia says
Simple Network Paging Protocol (SNPP) is a protocol that defines a method by which a pager can receive a message over the Internet. It is supported by most major paging providers, and serves as an alternative to the paging modems used by many telecommunications services. The protocol was most recently described in RFC 1861. It is a fairly simple protocol that may run over TCP port 444 and sends out a page using only a handful of well-documented commands.
something else that will be helpful is if you have a CRA at yow package.json add a new prop call proxy and the url of yow back if you add it all your cors problems will desapear
"proxy": "http://localhost:8080"
and now all your fetches need to have a relative url
instead of
fetch("http://localhost:8080/api/login")
they have to be like
fetch("/api/login")
NOTICE: how the proxy prop at the package.json doesnot ends with an / and how them fetches do start with it / if you add that to your package you'll be able to add cookies and stuff. as the whole thing will be like if back and front had the same port
I have an AngularJS app which talks to an ASP.Net WebApi backend.
Both the UI and the API are hosted on the same domain/server, but on different ports:
UI: https://www.example.com
API: https://www.example.com:8888
The UI is successfully communicating with the API for all required HTTP Methods (GET, POST, etc.), but I cannot get authentication to work.
When the call to "/login" is made, I get the following response from the API:
Access to XMLHttpRequest at 'https://www.example.com:8888/api/login' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Excerpt of Web.Config from ASP.Net WebApi
<configuration>
<system.webServer>
...
<httpProtocol>
...
<customHeaders>
<clear />
<!-- CORS Configuration -->
<add name="Access-Control-Allow-Origin" value="https://www.example.com" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
<!-- /CORS Configuration -->
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
There is no other CORS-related configuration within the API app.
Call to authenticate from AngularJS front-end
attemptLogin (userId, password) {
var data = {
UserId: userId,
Password: password
};
return this.$http.post("https://www.example.com:8888/login", data, { withCredentials: true });
}
Interestingly...
... if I set the "Access-Control-Allow-Origin" header to wildcard "*", I get a different message, which would indicate that the API is correctly identifying the API call as relating to authentication.
Access to XMLHttpRequest at 'https://www.example.com:8888/api/login' from origin 'https://www.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Can anyone shed any light on what I'm doing wrong?
You might need to include the port you're using on UI. Like this:
<add name="Access-Control-Allow-Origin" value="https://www.example.com:4200" />
this is murugan. I'm a newbie to firebase cloud functions, So what i did wrote a FCF to send a email notification to whom i want send with node mailer
mailOptions ={
from: '"my test app" <murugansakthivel.pk#gmail.com>',
to:emails,
subject:"My First cloud functions",
text:emailText,
};
then i deployed it in the firebase and it successfully deployed it. Following then i used the url to from my angular js code like below,
var url = 'https://us-central1-myappname.cloudfunctions.net/sendEmail';
var config = {
data : {
employees: answer.selectedEmployees,
title: cnt.Title
},
headers:{
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*'
}
}
$http.post(url, data, header).then(function (success) {
result = result + ' &' + success;
_callSuccessCntMessage(action, result);
});
I'm writing this code in visual studio 2013. when i invoked this function then got a error saying
"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:9137' is therefore not allowed access. "
Then i googled about it, following i got suggestion saying add below code in the FCF
const express=require('express');
const cors= require('cors')({origin:true});
const app=express();
app.use(cors);
request.header('Access-Control-Allow-Origin', '*');
request.header('Content-Type','application/json');
request.header('Access-Control-Allow-Headers', 'Content-Type');
added it in code then deployed the cloud functions. The error remains the same.
I'm still not able find a solution for this. Please don't mark this as duplicate my situation is completely different from others issue.
I'm desperately needing help. Thanks in advance.
You can set config allow-origin in web.config file of localhost:9137 project:
web.config
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
With this config you have permission to this port, also you can customize it by add custom port to it:
<add name="Access-Control-Allow-Origin" value="http://localhost:1506, http://localhost:1502" />
With this config just ports 1506 and 1502 has allow to get from port 9137
you can use the following steps for testing it in local environment :
Step 1 - Press windows + r
Step 2 - Copy chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security there.
Step 3 - run your localhost in the chrome opened.
But this is for local development only. For Production you have to use SSL certificates.
I have been struggling on the CORS issue since one week. I am writing web services using web api2. I created one controller(for basic crud operations) and hosted in server 192.168.0.213:8041/api/user_creation and i created another mvc5 application and hosted in the same server as http://192.168.0.213:8040/usercreation/Index. I have enabled cors using the below link.
http://www.c-sharpcorner.com/UploadFile/009ee3/implementation-of-cross-origin-request-in-Asp-Net-web-api-2/
I am using angularjs to fetch services as below. I able to get data from server and also I am able to push data to server. So my GET and POST verbs are working fine. Whenever i tried to update and delete i am facing issues and getting below error message.
Failed to load resource: the server responded with a status of 405 (Method Not Allowed) http://192.168.0.213:8041/User_Creation/1020
XMLHttpRequest cannot load http://192.168.0.213:8041/User_Creation/1020. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.213:8040' is therefore not allowed access. The response had HTTP status code 405.
I am using angularjs to call web services as below.
For example for update,
this.update = function (sub) {
var url = 'http://192.168.0.213:8041/User_Creation/' + sub.user_id;
return $http({
method: 'put',
data: JSON.stringify(sub),
url: url,
contentType: "application/json"
});
}
For delete,
this.deleteSubscriber = function (user_id) {
var url = 'http://192.168.0.213:8041/User_Creation/' + user_id;
return $http.delete(url).then(function (response) {
return response.data;
});
}
From Web Api I am receiving data in the form of json so i added below code in global.asx.
GlobalConfigGlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
This is my handler code in web.config
<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>
Below are request and response data.
Request URL: http://192.168.0.213:8041/User_Creation/1021
Request Method: DELETE
Status Code: 405 / Method Not Allowed
- Request Headers
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 0
Host: 192.168.0.213:8041
Referer: http://192.168.0.213:8040/usercreation/Index
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
- Response Headers
Allow: GET, HEAD, OPTIONS, TRACE
Content-Length: 1293
Content-Type: text/html
Date: Mon, 16 Jan 2017 08:34:30 GMT
Server: Microsoft-IIS/8.5
X-Powered-By: ASP.NET
I am facing problem with PUT and Delete method. May i get some help on this? Can someone tell me where i am doing wrong? Thank you.
It looks like PUT and DELETE verbs are not allowed on your web server and the issue you are having is not related to CORS at all. There are a couple of things you might want to checkout to ensure that those verbs are allowed in the first place. Before trying to make cross domain AJAX calls, make sure that you can make standard HTTP calls to your Web API and that it responds to those verbs.
So in your web.config you might have something like this:
add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Notice the absence of PUT and DELETE verbs here.
Also make sure that you have removed all WebDAV and WebDAVModule traces from your web.config as this might be interfering with your requests:
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
Now that you can successfully call your Web API endpoints using the PUT and DELETE verbs using Postman or Fiddler you may go back to the javascript attempts.
I have problem with cross domain request to an API hosted on IIS.
I am using an angularjs application to fetch data from the API, which is developed with laravel 5 using tymondesigns/jwt-auth and barryvdh/laravel-cors package for JWT and CORS.
When the API is hosted on apache angularjs app fetches data.But when hosted on IIS it gives following error:
XMLHttpRequest cannot load http://example.com/api/authenticate. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
The preflight request response header:
Request URL:http://example.com/api/authenticate
Request Method:OPTIONS
Status Code:200 OK
Allow:OPTIONS, TRACE, GET, HEAD, POST
Content-Length:0
Public:OPTIONS, TRACE, GET, HEAD, POST
Server:Microsoft-IIS/8.5
X-Powered-By:ASP.NET
My first question is why "Access-Control-Allow-Origin" is not set, when hosted on IIS. Is there any special setting to enable CORS on IIS.
So then I added following lines to web.config file:
<httpProtocol>
<customHeaders>
<remove name="Access-Control-Allow-Origin" />
<add name="Access-Control-Allow-Origin" value="*" />
<remove name="Access-Control-Allow-Headers" />
<add name="Access-Control-Allow-Headers" value="Origin, Content-Type, Authorization, Accept, X-Request-With" />
</customHeaders>
</httpProtocol>
Now it give following error:
XMLHttpRequest cannot load http://example.com/api/authenticate. The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost, *', but only one is allowed. Origin 'http://localhost' is therefore not allowed access.
The preflight request response header:
Request Method:OPTIONS
Status Code:200 OK
Access-Control-Allow-Headers:Origin, Content-Type, Authorization, Accept, X-Request-With
Access-Control-Allow-Origin:*
Allow:OPTIONS, TRACE, GET, HEAD, POST
Public:OPTIONS, TRACE, GET, HEAD, POST
Server:Microsoft-IIS/8.5
X-Powered-By:ASP.NET
The actual request response header:
Request Method:POST
Status Code:200 OK
Access-Control-Allow-Headers:Origin, Content-Type, Authorization, Accept, X-Request-With
Access-Control-Allow-Origin:http://localhost
Access-Control-Allow-Origin:*
Content-Type:application/json
Server:Microsoft-IIS/8.5
Set-Cookie:XSRF-TOKEN=eyJpdiI6IkpwNnU2mTnc9PSIsInam9jTFpxb0ptak1IMmFsQ3ZZhbMTM5ZTMzMjgyZWIyNCJ9; expires=Thu, 27-Aug-2015 12:52:55 GMT; Max-Age=7200; path=/; httponly
Vary:Origin
X-Powered-By:ASP.NET
X-Powered-By:PHP/5.6.0
So Why "Access-Control-Allow-Origin" is repeating" on actual request response header.
Is it secure to add "Access-Control-Allow-Origin" to web.config file.
The proper solution for this issue is to:
Install the CORS Module in IIS and
Configure CORS in web.config file
IIS CORS module Configuration Reference