I created WCF service and WPF client to send to service some stream. GET method works fine in my client but i have problem with POST method. Here is the code:
IRestService:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "SaveFromStreamJson2")]
void SaveFromStreamJson2(Stream stream);
RestService.svc
public void SaveFromStreamJson2(Stream stream)
{
if (stream != null)
{
StreamReader stReader = new StreamReader(stream);
string text = stReader.ReadToEnd();
}
}
WCF client:
private void button2_Click(object sender, RoutedEventArgs e)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:57424/RestService.svc/SaveFromStreamJson2");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"test\"," + "\"password\":\"bla\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Related
I have a WCF POST Method - it looks like below:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UploadReport/{customerId}/{author}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string UploadReport(string customerId, byte[] fileData, string author);
It is used to upload a Report to an ECM Client I am using.
I was calling this with a WCF Client in another solution by adding the Service reference to the WSDL. So as below:
using (MemoryStream mem = new MemoryStream())
{
ExcelReportGenerator excel = new ExcelReportGenerator();
success = excel.CreateExcelDoc(mem, customerId);
mem.Position = 0;
try
{
using (CustomerClient.UploadClient customerClient = new CustomerClient.UploadClient())
{
customerClient.Endpoint.Binding.SendTimeout = new TimeSpan(0, 10, 0);
uploadReportId = customerClient .UploadReport(customerId.ToString(), mem.ToArray(), userId.ToString());
}
//remaining code removed from brevity
However now I need to make this call from a HttpWebRequest rather than using the generated wcf client.
However, I am wondering how to do this in order to POST the byte array as well as the customer id and author.
I have used something like the below for a simple API GetRequest before
string jsonResponse = string.Empty;
string requestUri = string.Format("{0}", myAPI);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Credentials = new NetworkCredential(userNameWs, passwordWs);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
jsonResponse = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
IN the above myAPI was loaded from config and looked like below:
http://localhost/myWS/api/Reference/GetAllCarManufacturers
I know to make it hit my WCF Method I would need
request.Method = "POST";
What would I need in order to POST the fileData and hit the Post URL which in the WCF is in the format "UploadReport/{customerId}/{author}
I have a WCF Service that I start up in VS2015. Then Client code in another VS2015.. I keep getting "the remote server returned an error (404) Not Found" Error. When I add parameter to URL "http://localhost:53989/FileShareService.svc/UploadFile/WTM" is works fine but if I add as encoding.GetBytes I get the error.
[ServiceContract]
public interface IFileShareWebService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "UploadFile/{patron}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
void UploadFile(string patron);
}
Client Code Not Working:
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "patron=WTM";
byte[] data = encoding.GetBytes(postData);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:53989/FileShareService.svc/UploadFile/WTM");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = 0;
//httpWebRequest.GetRequestStream();
// Code to write data to the stream
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Client Code Working:
var httpWebRequest =(HttpWebRequest)WebRequest.Create("http://localhost:53989/FileShareService.svc/UploadFile/WTM");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = 0;
httpWebRequest.GetRequestStream();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
How to Send and receive excel data using web service
I have created a web application to send excel file data to a web service.
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:58959/RESTServiceImpl.svc/PostFile");
request.ContentType = "application/vnd.ms-excel";
request.Headers.Add("filename", "fooBar.xls");
request.Method = WebRequestMethods.Http.Post;
byte[] fileData = System.IO.File.ReadAllBytes("C:\\Users\\Public\\Documents\\Forecast Pro TRAC\\Input\\Book1.xls");
request.ContentLength = fileData.Length;
using (System.IO.BinaryWriter postStream = new System.IO.BinaryWriter(request.GetRequestStream()))
{
postStream.Write(fileData);
postStream.Flush();
postStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.Diagnostics.Debug.Assert(response.StatusCode == HttpStatusCode.OK);
string responseMessage = string.Empty;
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
responseMessage = sr.ReadToEnd();
}
System.Diagnostics.Debug.WriteLine(responseMessage);
}
Now I need to receive that excel data from WCF application. So I have done something like below code. I am getting total bytes that I am sending. What are exact things I need to do in both end to send and receive excel data.
[ServiceContract]
public interface IRESTServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "PostFile")]
string PostFile();
}
public class RESTServiceImpl : IRESTServiceImpl
{
public string PostFile()
{
var httpRequest = HttpContext.Current.Request;
var bites = httpRequest.TotalBytes;
return httpRequest.FilePath;
}
}
I am very new in web service and this is my first application. So please please help me.
Thanks in advance.
I have solved the solution and here is the working code
public class RestServiceImpl : IRestServiceImpl
{
public string PostFileRest(Stream fileContents)
{
var httpRequest = HttpContext.Current.Request;
var filePath = "C:\\file.xls"; //excel filePath for local
var bites = httpRequest.TotalBytes;
//Convert stream to byte array
byte[] reqBytes = readRequest(fileContents, bites);
byte[] decodedReqBytes = HttpUtility.UrlDecodeToBytes(reqBytes);
string json = System.Text.Encoding.UTF8.GetString(reqBytes);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);
MemoryStream stream = new MemoryStream(reqBytes);
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
stream.WriteTo(file);
file.Close();
stream.Close();
return json ;
}
#region Convert Stream to byte array
private byte[] readRequest(Stream fileContents, int bites)
{
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
int BUFFER_SIZE = bites;
int iRead = 0;
int idx = 0;
Int64 iSize = 0;
memStream.SetLength(BUFFER_SIZE);
while (true)
{
byte[] reqBuffer = new byte[BUFFER_SIZE];
try
{
iRead = fileContents.Read(reqBuffer, 0, BUFFER_SIZE);
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
if (iRead == 0)
{
break;
}
iSize += iRead;
memStream.SetLength(iSize);
memStream.Write(reqBuffer, 0, iRead);
idx += iRead;
}
byte[] content = memStream.ToArray();
memStream.Close();
return content;
}
#endregion
}
The Interface-
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "PostFileRest")]
string PostFileRest(Stream fileContents);
}
I have a WCF project that returns a DataSet in XML format. This is in my service contract:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "RunSavedReportByID", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
DataSet RunSavedReportByID(int savedReportID);
I have another project that consumes this service, and I'm trying to get the DataSet back. I call my service like so:
strResults = objUtility.GetData("RunSavedReportByID", JsonConvert.SerializeObject(new { savedReportID = savedReportID }));
GetData looks like this:
public string GetData(string method, string data)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(externalServiceUrl + method);
ASCIIEncoding encoding = new ASCIIEncoding();
var postData = encoding.GetBytes(data);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(postData, 0, data.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
return reader.ReadToEnd().Trim();
}
}
}
}
}
catch (Exception ex)
{
string error = ex.Message;
}
return null;
}
The string that I get is weird. It looks like this when I save it to a text file:
"\"<DataSet><xs:schema id=\\\"NewDataSet\\\" xmlns:xs=\\\"http:\\/\\/www.w3.org\\/2001\\/XMLSchema\\\" xmlns:msdata=\\\"urn:schemas-microsoft-com:xml-msdata\\\"><xs:element name=\\\"NewDataSet\\\" msdata:IsDataSet=\\\"true\\\" msdata:UseCurrentLocale=\\\"true\\\"><xs:complexType><xs:choice minOccurs=\\\"0\\\" maxOccurs=\\\"unbounded\\\"><xs:element name=\\\"Table\\\"><xs:complexType><xs:sequence><xs:element name=\\\"InvoiceNo\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"GuestID\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"ConsumerID\\\" type=\\\"xs:long\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"ContactTitleName\\\" type=\\\"xs:string\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"LastName\\\" type=\\\"xs:string\\\" minOccurs=\\\"0\\\"\\/><xs:element name=\\\"FirstName\\\" type=\\\"xs:string\\\" ... blah blah blah ... \\/NewDataSet><\\/diffgr:diffgram><\\/DataSet>\""
Not surprisingly, after I create and XmlDocument and call LoadXml, I get
Data at the root level is invalid. Line 1, position 1.
If I strip out the first and last quotation marks and unescape the string like so
strResults = Regex.Unescape(strResults);
strResults = strResults.Remove(0, 1);
strResults = strResults.Remove(strResults.Length - 1, 1);
then the XML loads fine, so the XML itself is legit.
So after all this exposition, my questions are
1) Why does the string I get back look so weird? What's up with all the extra quotation marks and backslashes?
2) Is there a better way of getting rid of the bad stuff before loading the XML?
I am bit new in rest service
I have service as below
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate="AuthenticateJSON/?username=username&password=password")]
public Response.Authenicate Authenticate(string username,string password)
{
var returnObject = new Authenicate();
try
{
returnObject.Response = "True";
}
catch (Exception exceptionObject)
{
returnObject.IsError = true;
returnObject.ErrorMessage = exceptionObject.Message;
}
return returnObject;
}
And I consume Service by below code
string input = #"{'himanshu','password'}";
var newUser = new User();
newUser.username = "username";
newUser.password = "username";
var input = new JavaScriptSerializer().Serialize(newUser);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:20620/Services/User/OperationActiveDirectory.svc/AuthenticateJSON/?username=username&password=password");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";//POST/GET
string responseText = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(input);//any parameter
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = streamReader.ReadToEnd();
}
but i am facing below error while execution
Could some one suggest me what i am doing wrong here