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";
}
}
Related
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;
}
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.
I have a rest service.
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/AddNews", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool Add(News entity);
Here the imp :
public bool Add(News entity)
{
try
{
_ctx.News.Add(entity);
_ctx.SaveChanges();
return true;
}
catch (Exception ex)
{
// TODO log this error
return false;
}
}
I post data to my service but i need the result of my operation that here is bool .how can i get the result in my code ?
News student = new News
{
Id = Guid.NewGuid(),
Subject = "wfwf",
ViewerCounter = 1, // removed the "" (string)
MainContent = "fsdsd", // renamed from "Content"
SubmitDateTime = DateTime.Now,
ModifiedDateTime = DateTime.Now,
PublisherName = "sdaadasd",
PictureAddress = "adfafsd",
TypeOfNews = "adsadaad"
};
WebClient Proxy1 = new WebClient();
Proxy1.Headers["Content-type"] = "application/json";
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer serializerToUplaod = new DataContractJsonSerializer(typeof(News));
serializerToUplaod.WriteObject(ms, student);
Proxy1.UploadData("http://localhost:47026/NewsRepository.svc/AddNews", "POST", ms.ToArray());
Just use this:
byte[] a= Proxy1.UploadData("http://localhost:47026/NewsRepository.svc/AddNews", "POST", ms.ToArray());
string result = System.Text.Encoding.UTF8.GetString(a);
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.
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)
{
...
}