REST Service receive empty params - c#

I'm trying to comunicate with my rest service but this one return always that my sended parameter is empty but in my client console he is filled.
Here is the Interface Class :
[ServiceContract]
public interface IMyTest
{
[OperationContract]
[WebInvoke(UriTemplate = "TestMe", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped)]
string TestMe(string parameter);
}
My svc method :
public string TestMe(string parameter)
{
if (string.IsNullOrEmpty(parameter)
return "Empty";
return "OK";
}
My client :
string content = "{\"Param\" : \"TEST\"}";
var request = WebRequest.Create("http://localhost/MyTestURL/MyTest.svc/TestMe");
request.Method = "POST";
request.ContentType = "application/json";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(content);
}
var res = (WebResponse)request.GetResponse();
StreamReader reader =
new StreamReader(res.GetResponseStream(), Encoding.UTF8);
System.Console.WriteLine("Response");
System.Console.WriteLine(reader.ReadToEnd().ToString());
Is my client code not ok ? My conifiguration not ok ? ...
Thanks.

If you want to get request as string, use Stream instead of String parameter
public void TestMe(Stream dataStream)
but if not, use serializable to Json objects as parameters.

i founded a good tutorial that helped me to implement the method with the stream parameter. thanks.

Related

Consume WCF service get error after the service change the return type

I created the WcfService and it worked fine. Now I need to to change the return value from int to List. After modified I get the error "The remote server returned an error: (500) Internal Server Error" on my test webpage. Also the other methods that I didn't modify get the same error too. Would someone tell me how to make it works.
The page to send the request:
protected void getOrders_Click(object sender, EventArgs e)
{
string serviceUrl= url + "/checkOrders?OrderNum=test123";
string result = "";
HttpWebRequest request = WebRequest.Create(serviceUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
lbl.Text = result;
}
There is the code on my IServer.CS
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "checkOrders?OrderNum={OrderNum}")]
//int getAllOrders(string input);
List<OrderDetails> getAllOrders(string input);
[DataContract(Name = "OrderDetails")]
public class OrderDetails
{
[DataMember]
public List<OrderDetails> lstOrderDetails;
}

Passing parameters to WCF using RestSharp

I have the following WCF service:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string UpdateReturnedPatients(string lst);
And I am calling it using RestSharp like this:
Ids id = new Ids();
id.id = "EMR0037933";
var client = new RestClient("https://myweb.com/services/Service1.svc");
var request = new RestRequest("UpdateReturnedPatients", Method.POST);
request.RequestFormat = DataFormat.Json;
string json = JsonConvert.SerializeObject(id);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("lst", json);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content;
But when I run the code, I have this returned:
Request Error:
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding.
What is the problem, and how I can pass the parameter (in my case named lst) to the web-service?
I can use methods other than RestSharp.
UPDATE
Changed web service to:
[WebInvoke(Method = "POST", UriTemplate = "UpdateReturnedPatients", RequestFormat =
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle =WebMessageBodyStyle.Bare)]
string UpdateReturnedPatients(Ids lst);
and The implementation of it is
public string UpdateReturnedPatients(Ids lst)
{
try
{
string json = JsonConvert.SerializeObject(lst);
return json;
}
catch (Exception ex)
{
throw;
}
}
And I used
request.AddBody(new { lst = id});
instead of AddParameter()
but the response is :
"{\"id\":null}"
It is not returning the value of the id field, even though I did supply it.

WCF service return JSON returned by yet another service

I am trying to write a WCF service (A) that is in turn calling another service (B). This is not a problem. The problem is that B returns json, and this I want to return from A. Here is the code I have:
public class Service1 : IService1
{
public string GetData(int value)
{
WebRequest wr = WebRequest.Create("//url_to_B//");
String username = "user";
String password = "password";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
wr.Headers.Add("Authorization", "Basic " + encoded);
Stream resStream = wr.GetResponse().GetResponseStream();
StreamReader resReader = new StreamReader(resStream);
String response = resReader.ReadToEnd();
resReader.Close();
resStream.Close();
return response;
}
}
and:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
}
Outputs as found in Fiddler:
B:
[{"id":"10103","key":"CAMMOT"}]
A:
"[{\"id\":\"10103\",\"key\":\"CAMMOT\"}]"
The returned value from A if called is a string with data that can be parsed to json. How would I go about returning json instead? Any help appreciated. Thanks.
By returning a Stream, you can return a raw string:
public class Service1 : IService1
{
public System.IO.Stream GetData(int value)
{
WebRequest wr = WebRequest.Create("//url_to_B//");
String username = "user";
String password = "password";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
wr.Headers.Add("Authorization", "Basic " + encoded);
return wr.GetResponse().GetResponseStream();
}
}
WCF binding will use jsonSerializer as MessageEncoder if you specify
ResponseFormat = WebMessageFormat.Json
Then it will process string as part of Json object (a property) and encode the " as \" to avoid conflict with the json syntax.
Just remove the ResponseFormat = WebMessageFormat.Json and it should work as you want.

Passing Json as stream to WCF method

I have created a website using WCF REST Service Template 40(CS) and It has a service method like this:
[WebInvoke(UriTemplate = "CTNotification", Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public string CTNotification(Stream contents)
How can I pass json to it ? I can not make the service parameter as string because client will be sending json as stream. How can I make a post call using C# to this service method with content type = application/json
Regards,
Asif Hameed
I'm not sure if you are doing this Synchronously or sync, but here is how to pass your args. The implementation may differ based on the needs of the client
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(ServiceAddress + "CTNotification/");
//parameters
byte[] data = Encoding.UTF8.GetBytes(jsonString);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
httpWReq.Timeout = 1000;
using (Stream newStream = httpWReq.GetRequestStream())
{
newStream.Write(data, 0, data.Length);
}

When I pass xml string as a request i get an Bad Request exception in WCF REST?

Client:
string value = "<?xml version=1.0?><person><firstname>john</firstname><lastname>smith</lastname> <person/>";
using (HttpResponseMessage response = m_RestHttpClient.Post("new/customerxml/"+value2, frm.CreateHttpContent()))
{
}
Server:
[OperationContract]
[WebInvoke(UriTemplate = "new/customerxml/string={value}", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml)]
public string NewCustomer(string value)
{
return value;
}
That's because WCF sniffs the content and decides you are uploading XML, not a string. Assuming you are using the HttpClient from the WCF REST Starter kit, try this:
string value = "<?xml version=1.0?><person><firstname>john</firstname><lastname>smith</lastname> <person/>";
var content = HttpContentExtentions.CreateDataContract(value, typeof(string));
using (HttpResponseMessage response = m_RestHttpClient.Post("new/customerxml/"+value2, content)
{
...
}

Categories