I am migrating an Ionic v1 application to Ionic v2. In one of my methods I make a call to a WCF service. In AngularJS I do it like this:
$http({
method: 'POST',
url: url,
data: JSON.stringify({ dato: 11 }),
dataType: "json",
contentType: "application/x-www-form-urlencoded"
})
And in Angular2 like this:
let data = JSON.stringify({ dato: 11 });
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers });
this.http.post(url, data, options)
.subscribe(data => {
console.log(data);
}, error => {
console.log("Error");
});
However, I receive from my C# service an error and says that the format I send to my functions is 'RAW' while waiting for it to send JSON with Angular 2
This error occurred to me in AngularJS but it was solved by adding the code I previously left in this post.
EDIT
My WCF service :
[OperationContract]
[WebInvoke(UriTemplate = "/GetCaptaciones", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json , BodyStyle = WebMessageBodyStyle.Wrapped)]
List<Captacion> GetCaptaciones(int id_captador);
AND
let data = JSON.stringify({ id_captador: 11 });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url + "/GetCaptaciones", data, options).subscribe(data => {
console.log(data);
});
Not working,
But if I test from POSTMAN this works
This:
let data = JSON.stringify({ dato: 11 });
and this:
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
are terribly contradictory and inconsistent.
Please try to be consistent when you make an HTTP request against a web server about how you are going to encode the request. So if intend to send a JSON body make sure that you specify the proper Content-Type request header, so that the server would know how to process this payload:
let headers = new Headers({ 'Content-Type': 'application/json'});
In addition to what Darin has said I would say you are not using BodyStyle = WebMessageBodyStyle.Wrapped correctly.
See your wcf method expects a single parameter so you could go ahead without wrappedrequest property.
[OperationContract]
[WebInvoke(UriTemplate = "/GetCaptaciones", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json)]
List<Captacion> GetCaptaciones(int id_captador);
Wrapped request means there should be some wrapper object on top of the input properties which WCF method takes as argument.
So something like this
var input =
{
"CaptacionesInput":
{
"id_captador": 11
}
};
Now wcf method becomes like
List<Captacion> GetCaptaciones(CaptacionesInputType CaptacionesInput);
Related
This is probably a very common problem but I couldn't get through it with the solutions from internet . First let me introduce the issue ,
I have a Rest WCF service exposed as follows :
// Service operation that retrieves the KPI result
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/KPI/{monthYear}/{currentYear}/{companyCode}/{divisionCode}/{shopCode}/{parameterName}/{kpiCode}")]
int Get_SY_KPI(string monthYear,string currentYear,string companyCode, string divisionCode, string shopCode, string parameterName, string kpiCode);
I'm trying to call this service from an html form with a simple ajax call :
$.ajax({
type: "GET",
url: "http://localhost:5547/FoxWcfRest.svc/KPI/March/2014/001/001/003/END_QUANTITY_INDICATOR_HP/002",
contentType: "application/json; charset=utf-8",
success: function(response) {
alert(response);
},
error: function()
{
alert("Oops");
}
});
I'm not sure what's going wrong but I'm getting null alert msg , I've read something about crossdomain issues .. anybody could help ?
I have a Web Service (C#, non-WCF) that should return JSON to mobile app clients, it has an API function like this:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public Animal AnimalInformation(int animalID) {
Animal animal = new Animal();
animal.name = AnimalNameForID(animalID);
animal.color = AnimalColorForID(animalID);
return animal;
}
Although its response format is set to JSON, the response it displays in the browser is still XML, like this:
<Animal>
<Name>Vicky</Name>
<Color>Grey</Color>
</Animal>
I've been looking around for an answer and found out that this is related to the client's reception format, according to this thread, and the thread suggests to use this piece of javascript code to view the JSON return:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8;",
url: "http://MyWebServiceURL",
data: JSON.stringify({ ParameterName: "DataToSend" }),
dataType: "json",
success: function (data, textStatus, jqXHR) {
//do something
},
error: function (jqXHR, textStatus, errorThrown) {
//fail nicely
}
});
I wasn't able to get this piece of js code to work, it always fails.
My questions:
1, Is there any settings can be set in my browser so that it asks for JSON instead of XML from the Web Service?
2, If not, are there any (simple) alternative solutions? I'm building this Web Service for my app, but I haven't started working on the app yet, so please don't suggest using app as the test client for WS
Check this out: stackoverflow.com/a/19564022/487940
Essentially, you want to flush the contents down the Response and set the ContentType of the response:
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
HelloWorldData data = new HelloWorldData();
data.Message = "HelloWorld";
Context.Response.Write(js.Serialize(data));
}
}
public class HelloWorldData
{
public String Message;
}
Testing with Fiddler and a client test page, I am receiving a 400 error when making an Ajax POST to my WCF service. A GET to the same url works fine though. I set a break point in the C# code on the service, but its not even getting into the method. I need some help determining what is wrong because I have no idea at this point. A similar POST worked fine previously, but I had to rewrite my Ajax call and I'm assuming I'm missing something out of that? Very confused and frustrated.
[OperationContract]
[WebGet(UriTemplate = "/{appName}/{custCode}/{custUserName}/",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
IList<Url> GetUrls(string appName, string custCode, string custUserName);
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped,
Method = "POST",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{appName}/{custCode}/{custUserName}/")]
ResponseAction SaveDeviceInfo(string appName, string custCode, string custUserName, DeviceInfo deviceInfo);
Here is my Ajax call on the client side:
var jsDeviceInfo = {
deviceUuid: 'Unique660',
deviceModel: 'Mark3',
deviceCordova: '2.3.3',
devicePlatform: 'Android',
deviceVersion: '3.3.0'
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost:xxx/Service.svc/testApp/custCode/userId",
data: JSON.stringify({ deviceInfo: jsDeviceInfo }),
processdata: false,
success: function (msg) {
alert(msg);
alert('Posted successfully');
},
error: function (msg) {
alert('Failed ' + msg.status);
}
});
I have a hard Microsoft Visual Studio 2008, I want to make cross domain query from your web service to a WCF service, but it does not work.
Ajax code on a web page:
$.ajax (
url: "http:/сите.com/ApplicationController.svc/HelloPost/"
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
alert (data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert (jqXHR textStatus errorThrown);<br/>
}
});
But my WCF service:
[OperationContract]
[WebInvoke (Method = "POST", UriTemplate = "HelloPost /", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[JSONPBehavior (callback = "callback")]
String GetPostHello (Stream data);
public String GetPostHello (Stream data)
{
HttpContext.Current.Response.AddHeader ("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader ("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader ("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader ("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End ();
return null;
}
return "Hello";
}
When a GET request with the domain it works, but try to make a POST request returns this header:
Content-Type application/json
Accept application/json, text/javascript, */*;q=0.01
Help, what could be the problem! Thank you!
For POST requests to be made cross-domain by browsers which support CORS (which is what you're using with the Access-Control headers), prior to the request the browser first sends a preflight request, which is a HTTP OPTIONS request, asking the server whether is ok to send the POST request to it. You can either add another operation which responds to the OPTIONS request, or you can implement full CORS support for WCF - it's not too simple, but I've wrote about it on http://blogs.msdn.com/b/carlosfigueira/archive/2012/05/15/implementing-cors-support-in-wcf.aspx with the steps required to make this work.
Here is part of my html file:
$('#btnMyButton').click(function () {
alert("message");
ajaxPost("Service1.svc/json/GetMethod", { "humanName": "anna" }, anotherMethod);
});
And here is the method being called:
public Human GetCustomer(string humanName)
{
Human x = new Human();
x.name = humanName;
return x;
}
But I got error - 400 bad request! How to fix it?
The body of the anotherMethod method is:
var txt = JSON.stringify(msg);
log("Result = " + txt);
Here is the name of the method:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
Human GetMethod(string humanName);
If you are trying to consume a JSON enabled WCF web service you may try the following:
$('#btnMyButton').click(function () {
$.ajax({
url: 'Service1.svc/json/GetMethod',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ humanName: 'anna' }),
success: function(result) {
// TODO: do something with the results
}
});
return false;
});
The JSON.stringify method shown here is natively built into modern browsers but if you need to support legacy browsers you might need to include the json2.js script.