Calling WCF service from jQuery in asp.net - wcf

I'm trying to call a WCF service using jQuery in asp.net
WCF service and asp.net website is under the same solution, however they run in different ports as below
WCF - http://127.0.0.1:54443/Service1.svc/
asp.net - http://127.0.0.1:57484/WebSite2/
Below is the WCF function code
[WebInvoke(Method = "GET",RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
public List<string> getCurrentTime()
{
List<string> lstrSampleDate = new List<string>();
lstrSampleDate.Add(DateTime.Now.TimeOfDay.ToString());
return lstrSampleDate;
}
and below is jquery code
$.ajax({
type: "GET",
url: "http://127.0.0.1:54443/Service1.svc/getCurrentTime",
// crossDomain: true,
datatype: "json",
success: function (rVal) {
//console.log
alert(rVal);
},
error: function (xhr, status) {
//console.log
alert('Error: ' + xhr.statusText + 'Status: ' + xhr.status);
},
complete: function (xhr, status) {
//console.log
alert("The request is completed!");
}
});
When i execute the code i get the below error get printed in console
> XMLHttpRequest cannot load
> http://127.0.0.1:54443/Service1.svc/getCurrentTime. Origin
> http://127.0.0.1:57484 is not allowed by Access-Control-Allow-Origin.
As a work-around i did add the below settings to config file (of website)
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
and still did get any fruitful result. can anyone point me where i'm missing?
Note: I've replaced 'localhost' with 127.0.0.1
Thanks

May be you'll find this post helpful: Access-Control-Allow-Origin error sending a jQuery Post to Google API's
I solved the Access-Control-Allow-Origin error modifying the dataType
parameter to dataType:'jsonp' and adding a crossDomain:true

Related

IIS 'Access-Control-Allow-Origin' header only on image uploading on ASP.NET 3.1

I currently have a VueJS frontend server where I make ajax requests using axios to my ASP.NET 3.1 backend API. When starting my project in debug or release in Visual studio, my form correctly works. The problem occurs only when publishing my web API on IIS. I've got a CORS Policy allow anything basically in my Web API's startup.
Cors Policy under Startup#ConfigureServices
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
Enabling my policy under Startup#Configure
app.UseCors("CorsPolicy");
Here is my axios request :
let data = new FormData()
if(this.file !== null)
data.append("Icons", this.file.file, this.file.file.name)
data.append('Id', this.itemId)
// append other data...
axios.defaults.headers.common['Authorization'] = 'Bearer ' + this.$store.state.token
axios.post(this.$store.state.api + 'items/edit', data).then(() => {
console.log('success')
}).catch(err => {
console.log(err)
})
The request is successful when no image is provided in the FormData. However, when an image is sent, it returns an error :
Access to XMLHttpRequest at 'https://exemple.com:5001/api/items/edit' from origin 'http://exemple.com has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This error only occurs when my application is published on IIS (6.2)
Using the comments by Lex Li and Brando Zhang, I added a CORS configuration to my web.config of the Web API project.
CORS Configuration :
<cors enabled="true">
<add origin="*" >
<allowHeaders allowAllRequestedHeaders="true" />
</add>
</cors>

API authtentication with a Ionic app

I am building a Ionic app that is supposed to communicate with an ASP net MVC application (I need to get JSON data).
When I send request to the ASP application from the Ionic app, I am not allowed because I am not logged. I get this :
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8100' is therefore not allowed
access. The response had HTTP status code 401.
My issue is that I want to log in to my API but I do not know how to proceed with Ionic. In a similar application, I used C# client and I was using an HttpWebRequest & NetworkCredential objects.
I made POST request to try to log in the API but I just get a 401 error.
Here is the code, but the credentials that I sent do not allow me to authenticate to the web service.
connect(){
var credentials = "name=" + mylogin + "&password=" + mypassword;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post(URLServeur, credentials, {headers: headers}).subscribe(data => {
if(data.json().success){
console.log("yes");
resolve(true);
}
else
{
console.log("no");
resolve(false);
}
});
}
Thanks,
I finaly found out that it is an issue in Angular with the parameters of the request. If you insert too much request options, withCredentials : true is ignored.
Code in Ionic app:
var headers = new Headers();
headers.append('Content-Type', 'application/json');
var url = "http://localhost"
var data = "This is my data";
this.http.post(url, JSON.stringify(data), {withCredentials: true}).subscribe(data => {
if(data){
console.log("yes");
}
else
{
console.log("no");
}
});
Also, do not forget to add this to webConfig file on server :
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="http://localhost:8100" />
<add name="Access-Control-Allow-Headers" value="content-Type,authorization" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
I hope it will help other people

ajax post works vs. angularjs $http does not work w/ ASP.NET MVC 4

I have two projects client side and server side.
Client side project is pure htmljs. Server side is ASP.NET MVC 4 and Web Api.
Because there are two projects I need to enable CROS functionality.
I added into server's webconfig:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
Ajax Post version which is working:
$.post(url, appContext).done(
function(data, textStatus, jqXHR) {
successFn(data, textStatus);
})
.fail(
function(jqXHR, textStatus, err) {
errorFn(err, textStatus);
});
angular $http Post version which is NOT working:
$http({
url: url,
method: 'POST',
params: { appContext: appContext },
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
/*'Accept': 'text/json'*/}
}).success(successFn).error(errorFn);
When I use $http I am getting two errors:
OPTIONS url 405 (Method Not Allowed)
POST url 500 (Internal Server Error)
ASP.NET MVC method is
[System.Web.Http.HttpPost]
public List<Module> GetModules([FromBody]SessionContext appContext)
{
return CreateModules();
}
EDIT:
Angular model's configuration:
var emsApp = angular.module('EmsWeb', ['ui.bootstrap']);
emsApp.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
Headers of OPTIONS request that I see in browser:
Request URL:http://localhost/EmsWeb/api/ModuleApi/GetModules?appContext=%7B%22globalDate%22%3A%22Mon%2C%2008%20Jul%202013%2013%3A09%3A35%20GMT%22%2C%22userToken%22%3A%22AlexToken%22%7D
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
DNT:1
Host:localhost
Origin:http://localhost:50463
Referer:http://localhost:50463/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Query String Parametersview sourceview URL encoded
appContext:{"globalDate":"Mon, 08 Jul 2013 13:09:35 GMT","userToken":"AlexToken"}
Response Headers
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:76
Content-Type:application/json; charset=utf-8
Date:Mon, 08 Jul 2013 13:09:35 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
Any ideas why angular way does not work are appreciated?
Update the issue as it turns out to be quite silly:
because I used params and instead of data in:
$http({
url: url,
method: 'POST',
params: { appContext: appContext },
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
/*'Accept': 'text/json'*/}
}).success(successFn).error(errorFn);
angular converted to GetRequest. No need for ContentType either.
so actual code is
$http({method: 'POST',
url: url,
data: appCtx,
}).success(successFn).error(errorFn);
so ALMOST resolved, I see that angular still issues OPTIONS request that fails but post request goes through...
so any ideas on that one are appreciated
My issue were due to two reasons:
I used params and instead of data in
$http({
url: url,
method: 'POST',
params: { appContext: appContext },
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
/*'Accept': 'text/json'*/}
}).success(successFn).error(errorFn);
angular converted to GetRequest. No need for ContentType either. so actual code is
$http({method: 'POST',
url: url,
data: appCtx,
}).success(successFn).error(errorFn);
on the server side
I needed something handling OPTIONS request. One way is to decorate method w/ [System.Web.Http.AcceptVerbs("OPTIONS")], which I do not think the best way.
Another way is to add Custom Message Handler.
I am still researching it...
If your ajax is working then it looks like the angular side of things isn't configured. Add this before you use $http (in your controller setup).
$http.defaults.useXDomain = true;
See this guys jsfiddle for a working example: http://jsfiddle.net/ricardohbin/E3YEt/
EDIT: Further to your comment and edit to the question, this post might help you: http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html
-Be sure about the syntax of get and Post and the way of sending parameters
-Check the expected Parameter that you expect at the destination action or method and be sure that the sending one and receiving one are the same.

Issue with url parameter calling WCF service from JQuery

I am trying to call the WCF service from Jquery. But if I replace the url with my machine name it doesn't work. The html/jquery and WCF are both on the same web site (project). I think many people need help with this since there is no way to debug and figure out the problem. Instead of continuously changing the wcf service file, web.config file and html (ajax function) page, does anyone have a running project with this issue?
$.ajax({
type: "POST",
//work well
//url: "Service1.svc/MyFunction",
//work well
//url: "http://localhost:43969/Service1.svc/MyFunction",
//not work ???
//url: "http://PWLL-IT-056:43969/Service1.svc/MyFunction",
data: '{"Count": "' + counter + '"}',
contentType: "application/json", // content type sent to server
success: ServiceSucceeded,
error: ServiceFailed
});
Thanks for help guys,

Googlemaps Api v3 getJson not working in IE

I have the following problem: I am trying to get data from the googlemaps api v3 via ajax with the code below. It works fine in Chrome and Firefox, but not in IE. What am I doing wrong?
var lat;
$.ajax({
url: "url",
cache: false,
dataType: "json",
success: function(data) {
lat = data.results[0].geometry.location.lat;
}
});
Add the following error event to your Ajax call
success: function(data) {
lat = data.results[0].geometry.location.lat;
},
error: function(xhr, status, error) {
alert(status);
}
And let us know what error message you get in IE, if any at all.
EDIT - Sounds like you are trying to do a cross-domain request?
If that is the case, try setting $.support.cors = true; before your ajax request.
Fetched from http://api.jquery.com/jQuery.support/
To enable cross-domain requests in environments that do not support cors yet but
do allow cross-domain XHR requests (windows gadget, etc), set
$.support.cors = true;
EDIT2 - Ill assume you are running IE9, in that case you need a plugin for jQuery found here:
https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js
Also see this answer on SO for more details on why a plugin is needed for IE9 (with cors): IE9 jQuery AJAX with CORS returns "Access is denied"
EDIT3 - Download jQuery.XDomainRequest.js and include it before your AJAX call.