How to send JSon array to remote asmx webservice using c#? - c#

In my application i've to send request to a remote asmx web service which is asking for a number of parameters. There is a parameter which is asking for json array. But i can't figure it out that how can i input my json string in the asmx url.(There is no issues with other string values for other parameters).
Thanks in advance.

It's my understanding that unless the webservice has been heavily customised, you are going to need to pass that parameter in the request body rather than as a GET parameter. For example (with jQuery):
var data = {
paramName: ['this', 'is', 'the', 'array']
};
$.post('service.asmx/Method?getParam1=herp&getParam2=derp', data)
.done(function(d)
{
console.log('Response: ' + JSON.stringify(d));
});
It's been a while since I used an ASMX service, and I'm not 100% positive that you can mix parameters like that. I have a feeling that if you put anything in the body, you have to put everything in it.

Related

UnityWebRequest.Post to send a task to ClickUp's API, encoding JSON improperly

So I'm writing a program in Unity that sends tasks to a ClickUp list. I've been able to send the request through Postman for testing properly, but whenever I try to send that request through Unity I get an error with the Json encoding:
{"err":"Unexpected token % in JSON at position 0","ECODE":"JSON_001"}
The code for the method is as follows. It's just a very basic tester method, so I know it's a little messy as is, but once I'm able to actually send the requests properly I want I'll re-write it with the full functionality.
private void SendDemoTask()
{
string jsonString = "{\"name\": \"Unity send from postman\",\"description\": \"Sent on May 24 2022\"}";
UnityWebRequest demoTaskRequest =
UnityWebRequest.Post($"https://api.clickup.com/api/v2/list/{listID}/task",jsonString);
demoTaskRequest.SetRequestHeader("Authorization",accessToken);
demoTaskRequest.SetRequestHeader("Content-Type","application/json");
var operation = demoTaskRequest.SendWebRequest();
// Wait for request to return
while (!operation.isDone)
{
CheckWebRequestStatus("Task creation failed.", demoTaskRequest);
}
Debug.Log(demoTaskRequest.result);
Debug.Log(demoTaskRequest.downloadHandler.text);
}
It seems to be an issue with the JSON encoding. Unfortunately the POST method doesn't have an argument to take a byte array. The PUT method does, but ClickUp's API won't accept the same types of requests through Put.
Is there a way for me to send this request that will correct the encoding issue? Or is the problem somewhere else?
Apologies if any part of this isn't clear. I'm fairly new to using UnityWebRequest and a total noob to webdev in general.
Thank you for any help you all can offer, I very much appreciate it!

C# WebAPI - getting URL with parameters passed as QueryString

I've been searching for this problem but non was identical to my case.
I have the following controller:
public HttpResponseMessage GetMyService(int aType, [FromUri] string streamURL)
streamURL is a parameter that gets a full URL sent by the client.
The client calls the service like that:
http://www.myservice.com/.../GetMyService/?aType=1&streamURL=http://www.client.com/?p1=100&p2=200
The problem is that at then end, I get the [FromUri] string streamURL parameter as http://www.client.com/?p1=100 without the &p2=200
This is known and reasonable, but I cannot place any encoding/decoding functionality as the URL is cut at the very beginning.
Any help would be appreciated..
THX
The client should properly URL encode the value of the streamURL query string parameter when making the request in order to conform to the HTTP protocol specification:
http://www.myservice.com/.../GetMyService/?aType=1&streamURL=http%3A%2F%2Fwww.client.com%2F%3Fp1%3D100%26p2%3D200
So basically there's nothing you could do on the server side, you should fix the client.

Using WebClient to pass arrays as part of message body for post action

I am writing a console application that needs to perform a POST to an MVC controller. I am using the WebClient class to perform the POST. But I'm having trouble understanding how to add arrays to the message body.
For simple parameters, it seems to work if I do this:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "userName", "userName" },
{ "password", "passwordGoesHere"}
};
byte[] responseArray = client.UploadValues(String.Format("{0}/Mobile/StartSession", serverAddress), values);
Debug.WriteLine(String.Format("\r\nResponse received was :\n{0}\n", Encoding.ASCII.GetString(responseArray)));
}
I was trying to find how to pass arrays in the message body when using WebClient (for calling one of the other methods). I came across this solution: POST'ing arrays in WebClient (C#/.net)
It appears the solution actually passes parameters in the query string (and not in the message body). This seems to work in any case, as the HttpPost method on the MVC controller is still receiving the correct information. However, another method requires that I pass an image as an array of bytes. This is too large to be passed in the querystring and so the call fails.
So my question is, using the code I provided above, how can I add arrays in there as well. So an array of bytes for example, but also an array of strings.
If any one can provide me with a solution it would be much appreciated, or if I'm incorrect in my thinking please let me know.
Thanks
Instead of using array of bytes maybe you should POST a file in the same way files are uploaded from browser from file inputs. This way you will save some transfered bytes, but you have to use HttpWebRequest instead of WebClient. More about this solution is here:
Upload files with HTTPWebrequest (multipart/form-data)
You upload bytes as "multipart/form-data" content type. On the server you will receive the streams of bytes in Request.Files collection.

RESTful web service returning XML not JSON

I have this simple web service, right now it just looks to see if the part number is A123456789 and then it returns a model number. This will be replaced by logic that will be connecting into a database to check the partno against and then return the actual model number. But at this point I just need it to return some dummy JSON data. However when I use Fiddler and look at the call in the web broswer of http://localhost:PORT/Scan/Model/A123456789 it returns this
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Model: CVS-1679</string>
But when I do a GET in fiddler of the same URI I get
"Model: CVS-1679"
Only under the textview tab.
Why is it being returned in XML (in the browser and text in Fiddler) and not JSON, when I have setup my ResponseFormat to be JSON?
My Code:
[WebGet(UriTemplate = "Model/{partno}", ResponseFormat = WebMessageFormat.Json)]
public string Model(string partno)
{
if (partno == "A123456789")
{
string modelno = "CVS-1679";
return "Model: " + modelno;
}
else
{
string modelno = "CVS-1601";
return "Model: " + modelno;
}
}
ASP.NET webservice return XML / SOAP message by default. In case you want to return Json string, you would need to decorate the Webservice with [ScriptService] attribute. This inform the IIS that this service would be used by ASP.NET AJAX calls. These attribute are part of System.Web.Extensions.
You can define the web method response format by decorating the webmethod with ScriptMethod attribute.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
However even after decorating the webservice and webmethod by these attribute, the response can still be in XML format. This behaviour happen when the client which makes the request does not set the Request Header content type as “application/json”.
Before return the method call from webmethod serialize to Json string using JavaScriptSerializer
Debugging WebService using Fiddler
It is quite easy to use fiddler to test webservice. Following figure is an example of how to call a Webservice which returns a json string. Note that the request content type is set to application/json. The parameters expected by webserivce is mentioed in the Request Body section.
Note that the request content type is set to application/json.
It is being returned in Json if you look at the format of the data you get...
key: value
or in your case
string Model = "CVS-1679"
When you view it in fiddler your seeing the raw serialization transport from one MS endpoint to the other. The serialisation & De-serialisation elements in the .NET framework take care of transporting it across the wire, so that when you get the object back into your .NET app at the calling end, you get a variable called Model with the value you expect.
If you try to send an entire class you'll see a lot of nested XML tags, but when you get the object in your code, you'll see a first class citizen in the object hierarchy.
The reason it appears in your browser is because, the browser doesn't know how to de-serialise it, and so just displays the text

how to pass a decimal number to a rest web service

I am wanting to pass a decimal number (1.23) to my WCF-REST web service.
I keep getting a 'resource cannot be found' error. I expect that I'm encountering some security feature of IIS where urls that contain a dot are a resource. Does anyone have a suggestion on how to pass a decimal number to my webservice?
Sample url... http://localhost/restdataservice.svc/echo/2.2
Operation Contract
[OperationContract]
[WebGet(UriTemplate = "echo/{number}")]
string Echo(string number);
And implementation
public string Foo(string number)
{
return number;
}
You should look at IIS log to see the problem. One thing that can cause such problem is UrlScan. It has UrlScan.ini config file, where you can find AllowDotInPath parameter. If it is set to 0, requests such as above would be rejected. Just change it to 1 (but don't forget to ensure, that you don't allow directory traversals by rejecting urls with ..).
You may want to consider sending that number to your resource in a request representation using a POST request.
This should work fine out of the box, I cannot reproduce this problem with a similar basic setup - are you sure the default route for your echo method is set correctly?
I had a similar problem calling a method on a WCF OData Server.
The problem was that a decimal parameter requires an 'm' at the end.
http://localhost/restdataservice.svc/echo/2.2m

Categories