Passing parameters to WCF using RestSharp - c#

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.

Related

Convert XML String to XML in WCF Service C#

I am sending a XML string in HTML back to my WCF Service C#.
<script>
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://localhost:3000/test");
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
let xml = `<?xml version='1.0'?><query><testNumber>5</testNumber></query>`;
xmlhttp.send(xml);
</script>
However, I am getting a 400 bad request error from my WCF Service C#. Not sure why.
// This is my IService
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/test", ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
string testXML(string testNumber);
// This is my service
public string testXML(string testNumber)
{
try
{
XDocument doc = XDocument.Parse(testNumber);
return "passed";
} catch (System.Xml.XmlException e)
{
Console.Write(e.ToString());
return "failed";
}
}

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;
}

Send dynamic object throught HTTP POST request in c#

I'm trying to send a dynamic object throught and HTTP POst request, but when I Receive that object, it is null.
I cannot USE JObject, cause I have a "virtual" api, and it does not accept JObjects.
I tried to send the type object and dynamic. Both of them do not work. Can some body help me ?
Here's my post request:
public static void Post(string uri, object parameter, string serviceName)
{
StringBuilder url = new StringBuilder();
url.Append(uri);
var client = GetClient(url.ToString(), 300, "application/json");
var urlParameters = GetUrlParameters(new List<KeyValuePair<string, object>>() { });
var response = client.PostAsync(
urlParameters,
new StringContent(
JsonConvert.SerializeObject(parameter).ToString(),
Encoding.UTF8,
"application/json")
).Result;
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception($"{serviceName}: {response.StatusCode}");
}
Here is where i Receive that post:
Interce for method:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "Teste")]
void Teste(object requestData);
Method implemented in class( this is acctually where i get the data):
public void Teste(object requestData)
{
var teste = requestData;
var t1 = JsonConvert.SerializeObject(requestData); // this returns {}; (empty)
}
Can you tweak your POST a bit to troubleshoot the issue a bit more? Something like the following? (not compiled)
var rawJson = await client.PostAsync(
urlParameters,
new StringContent(
JsonConvert.SerializeObject(parameter).ToString(),
Encoding.UTF8,
"application/json")
).Content.ReadAsStringAsync();
var mappedObj = JsonConvert.DeserializeObject<T>(rawJson,
new JsonSerializerSettings
{
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
// convert this to your logger
LogHelper.Instance.Warning(2000, string.Format("Failed object mapping: {0}\n{1}",
args.ErrorContext.Error, rawJson));
args.ErrorContext.Handled = true;
},
// set culture to mitigate mapping issues related to dates/numbers
// https://stackoverflow.com/a/34529198
Culture = CultureInfo.InvariantCulture
});

REST Service receive empty params

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.

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