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
Related
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 am doing post and get response using HttpClient to communicate with REST API as below:
public static string PostToAPI( string value)
{
var payload = new APIModel
{
CommandText = value
};
var stringPayload = JsonConvert.SerializeObject(payload);
var httpContent = new StringContent(stringPayload,Encoding.UTF8,"application/json");
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
HttpResponseMessage message=client.PostAsync("https://testAPI/test",httpContent).Result if (message.IsSuccessStatusCode)
{
string result = message.Content.ReadAsStringAsync().Result;
return result;
}
return string.Empty;
}
is there any other alternative or best way do it?
You can always use HttpWebRequest and HttpWebResponse. Try Below
try
{
var webAddr = "URL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application";
httpWebRequest.Method = "POST";
string str = "request string";
httpWebRequest.Headers["Authorization"] = "";
httpWebRequest.Headers["TenantId"] = "";
httpWebRequest.Headers["Client-Type"] = "";
httpWebRequest.Headers["Protocol"] = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
Console.WriteLine(str);
streamWriter.Write(str);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine("result=" + result);
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
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();
}
}
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 trying to create a webservice. I am successfully able to send HttpClient Request to web service and getting response too.
What I want ?
I am sending some HttpHeaders with the POST request like userAgent, or any CustomHeader. That Header I want to read in webservice method. I don't know how to get Header list ?
I created webservice in C#.
public class Service1 :IService1{
public string putData(Stream data)
{
string response = string.Empty;
try
{
HttpContext ctx = HttpContext.Current;
string headerValue = ctx.Request.Headers["tej"];
StreamReader reader = new StreamReader(data);
string xmlString = reader.ReadToEnd();
StringReader sr = new StringReader(xmlString);
MySqlCommand cmd = new MySqlCommand();
DataSet ds = new DataSet();
ds.ReadXml(sr);
//my logic here....
return "Passed";
}
catch (Exception ex)
{
return "Failed";
}
}
}
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "putdata")]
string putData(Stream sDatabase);
}
Please try following using WebOperationContext.Current.IncomingRequest object.
public class Service1 :IService1
{
public string putData(Stream data)
{
try
{
//reading headers
IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
WebHeaderCollection headers = request.Headers;
foreach (string headerName in headers.AllKeys)
{
Console.WriteLine(headerName + ": " + headers[headerName]);
}
//---- rest of the code
}
catch (Exception ex)
{
return "Failed";
}
}
}