how to pass large json string to web service using [webinvoke] - c#

I have a problem passing a large JSON string to a web service from the client side with a jQuery function. When the lenth of the string increases to 1000 characters, the web service throw an exception "Unspecified Network Error". Please let me know how to pass a large JSON value to a web service using [webinvoke].
Can we increase the size of url or whatever to fix this problem?

You can serialize your Json as object:
page.asp
var data1 = {
IdTest: ('<%= miAspVar %>'),
fono: telefono,
etc, etc
};
var strData = YAHOO.lang.JSON.stringify(data1)
callService(testLlamada, strData, EstadoLlamada, onError2);
function onError2(result) {
alert(result);
}
function EstadoLlamada(result) {
...
}

Related

How to post a c# Hashtable with nodejs to WCF (basichttpbinding)

I have to access a WCF with node js. In this WCF there is a function that has one parameter which is an Hashtable. I'm doing this by using the SOAP protocol.
I'm wondering if it's possible to do this without using XML. Simple variables types like integer, string, bool etc. are sent fine, but the Hashtable is not accepted.
var soap = require('soap');
var args = {
account_id: 'xxxxx',
username: 'xxxxxx',
password: 'xxxxx',
dotComLogin: false,
_hashtableArg: {
a: 'aaaa',
b: 'bbbb',
},
offset: 5,
offsetIterations: 10
};
var url = "http://localhost:55791/WCF.svc?wsdl";
soap.createClient(url, function(err, client) {
client.requestJobId(args, function(err, result) {
console.log(result);
});
});
I know that I can use the wcf.js module for NodeJs, but I don't want to write XML SOAP messages. Is this possible?

URL Encode form data

My app has a form for users to enter a string of content and a pass-key, which is posted to the server and encrypted. The users are given the encrypted value back. The app allows them to send the encrypted value back to the server with the pass-key and the server will decrypt the data and send it back in the response.
I can successfully post the data for encrypting and get my response back. The issue I have though is that the encrypted data contains characters that need to be URL encoded when the users post the encrypted data back.
This is the Angular 4 service function that requests the encryption.
encrypt(data: CryptoData): Promise<Result> {
let urlParameters = new URLSearchParams();
urlParameters.append('content', data.content);
urlParameters.append('key', data.key);
let body = urlParameters.toString();
return this.http
.post('/api/encrypt', body, this.options)
.toPromise()
.then(response =>
{
return response.json();
});
}
This gets back the encrypted result. Using a Content and Key value of:
content: Foo Bar
key: Test Key
result: AAAAABAAAACUdwXxU1tfClnbpOaKEqNVPuZSxL+cawqTxH+ZAFmDlBAAAAD6o/EFwKE9aDIU1WLOCDtBbY7ERTiKgsXr4pnsvkm+Et+qpJwLORrvPn9QzmJ1uFI=
The result up there is a Base64 string and it contains characters, such as +, that I need to URL encode when the user posts the data back.
What is the angular way to handle this? The backend server is ASP.Net Core and I'm open to changing how my implementation there is done to handle any changes on the Angular side. At the moment I'm posting the data with this function, which causes the + characters to be replaced with spaces.
export class EncryptService implements OnInit {
private options: RequestOptions;
constructor(private http: Http) {
this.options = new RequestOptions({
headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' })
})
}
decrypt(data: CryptoData) {
let urlParameters = new URLSearchParams();
urlParameters.append('content', data.content);
urlParameters.append('key', data.key);
let body = urlParameters.toString();
return this.http
.post('/api/decrypt', body, this.options)
.toPromise()
.then(response =>
{
return response.json();
});
}
}
The interface being passed in looks like this:
export interface CryptoData {
content: string;
key: string;
}
My ASP.Net Core API end-point looks like this:
[HttpPost("~/api/Decrypt")]
public IActionResult Decrypt([FromForm] CryptoRequest request)
{
string content = request.Content;
string key = request.Key;
// .....
return base.Ok();
}
Use base64URL instead on base64.
For Angular, use base64URL.
Run npm install base64url
In your service or component beneath your imports, add the following:
const base64url = require('base64url');
Use like this..
const b64URLresult = base64url(result);
There is an alternative way to add javascript packages using Typings and Definitely Typed.. Didn't work first try for me on this package so gave the above solution.
And in your controller. Use Microsoft.AspNetCore.WebUtilities.Base64UrlDecode

Invaild Json Result through Web Api in angular js

I have build a http post web api in asp which return the following string in Json
RootObject rootObject = new RootObject()
{
status = "User Registered"
};
msg = JsonConvert.SerializeObject(rootObject);
Below is my angular js controller in which I am consuming that web api
.controller('signupCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) {
$scope.signup=function(data){
var link = 'http://xxxxxxxxxxxxxxxxxxxxxx/api/Home/RegisterUser';
//using http post
//passing values to parameter
$http.post(link, {RegisterName : data.name, RegisterUserName : data.username, RegisterPassword : data.password , RegisterEmail: data.mail , RegisterMobile : data.mobile})
.then(function (res){ //if a response is recieved from the server.
$scope.response = res; //contains Register Result
console.log($scope.response);
});
}
})
With the above code I am getting following result in google chrome console
I am try to get that status only to match it value but I am unable to do so.
The doubt I am having is that json format
console.log(JSON.stringify($scope.response)) will do what you need.
If you're wanting those particular value, you can just access those and pass them to log.
console.log($scope.response.data['status']);
you get the json as :
$scope.response = res.data;
might be you require JSON.parse(res.data) or $.parseJSON(res.data) for getting json object

SignalR, passing an object from the HUB to the Client (MVC C#)

I've looked around at other questions but they don't seem to fully answer this question, I'm trying to pass an object via JSON to the client Javascript. I'm using Newtonsoft.Json to make the process easier, but I can't seem to recieve the object.
Here's the code:
When a connection is made, I call the Hub using start().done() in the client javascript:
//start comm with server
$.connection.hub.start().done(function () {
console.log('Grabbing playlist data');
Playlist.server.requestPlaylist();
});
This calls the following method, which is supposed to grab the object and pass it back:
public void requestPlaylist()
{
var playlistData = (from c in db.Playlist where c.ID > 0 select c).Include(h => h.Song).ToList();
Playlist player = new Playlist();
foreach (var item in playlistData)
{
player.ID = item.ID;
player.Profile = item.Profile;
player.Song.ID = item.Song.ID;
player.Song.name = item.Song.name;
player.upvotes = item.upvotes;
}
string jsonObject = JsonConvert.SerializeObject(player);
Clients.All.recievePlaylist(jsonObject);
}
SO here, I'm searching the database, getting the results and storing it into the playlist model, then using newtonsoft.json to convert the model into a json object (Its roughly the same principle they have as an example on their site).
The client javascript that is invoked from this is:
function recievePlaylist(jsonObject) {
console.log('test to recieve data: ' + jsonObject.ID + ' test.');
};
Now just for testing purposes I'm just logging out out to the console, but this come back with nothing:
"test to recieve data: test." is how it comes back.
What am I missing?
Because you convert the object to a string on the server before passing it to the client, the client receives a string. Your string representation of a json object doesnt have an ID property so the value will be "undefined".
On the client you can use this to convert the string to a json object:
jsonObject = JSON.parse(jsonObject);
Just add that line to the top of your recievePlaylist function.
Note: You shouldn't actually need to convert your server object to a json string on the server side. SignalR automatically converts your server side objects to json objects on the client.
If you call WebAPI and receive json response/result on client side (JavaScript/jQuery). The way is general for both SignalR or WebAPI in regards of parse jsone response and the use it as object.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

passing data from ios app to C# web service

I am trying to develop this iOS app that can communicate with a C# web service under the local network. I am using AFNetworking to achieve the communication. Now I have achieved reading xml data from the web service with the help of this tutorial, which means my app can connect to the web service, I think. But what I really want to do is, passing data from the app to the web service. I have write some sample code:
AFmyAPIClient *myClient = [AFmyAPIClient sharedClient];
NSMutableDictionary *requestArray = [NSMutableDictionary new];
NSString *details = [_listOfItems description];
float tempF= [_listOfItems totalPrice];
NSString *price = [NSString stringWithFormat:#"%f",tempF];
int tempI = 1;
NSString *table = [NSString stringWithFormat:#"%u",tempI];
[requestArray setObject:details forKey:#"details"];
[requestArray setObject:price forKey:#"price"];
[requestArray setObject:table forKey:#"table"];
[myClient postPath:#"setOrderDetails" parameters:requestArray success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
After I build and run this app, it generates this error message:
2013-11-03 16:25:48.654 HLR[16149:70b] <?xml version="1.0" encoding="utf-8"?>
<int xmlns="http://localhost/service/Service1.asmx">3</int>
2013-11-03 16:25:48.844 HLR[16149:70b] Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 500" UserInfo=0x8b5b140 {NSLocalizedRecoverySuggestion=Missing parameter: orderDetails.
, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0x8b5bb70> { URL: http://10.0.0.111/service/Service1.asmx/setOrderDetails }, NSErrorFailingURLKey=http://10.0.0.111/service/Service1.asmx/setOrderDetails, NSLocalizedDescription=Expected status code in (200-299), got 500, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x8b4e910> { URL: http://10.0.0.111/service/Service1.asmx/setOrderDetails } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 34;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Sun, 03 Nov 2013 05:25:34 GMT";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "2.0.50727";
"X-Powered-By" = "ASP.NET";
} }}
At my C# web service side, I have Web Methods like:
[Web Method]
public void setOrderDetails(String orderDetails)
{
//store orderDetails into a text file.
}
I am new to iOS developing, I don't understand what did I really pass to the web service when I invoke this method:
[myClient postPath:#"setOrderDetails" parameters:requestArray success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"success!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
Did i just pass a NSDictionary as a parameter to the C# web service? If that is what it is, what can I do with this NSDictionary at the web service side?
I don't know whether this is the right way to achieve passing data to the web service. What I really want to do here is to pass some strings to the web service, how can I achieve that?
Any suggestions would be much appreciated!
You are passing the XML content as URL parameters. You need to pass it in the body of the request. Here are a couple of questions addressing posting XML using AFNetworking:
Example on using AFNetworking to post XML?
AFNetworking - Making an XML POST request to REST service? How to form NSDictionary parameters?

Categories