Problems sending and receiving JSON between ASP.net web service and ASP.Net web client - asp.net

You would think with all the posts here that this would be easy to figure out. :| Well here is what should be a simple example. NOTE The web service is VB and the client is c#. The wb service sends and receives fine when called from JQuery. From .NET There is a problem,
If the service asks for a parameter as show below then the client's getresponse method gets error 500 Internal server error
The Web Service
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, XmlSerializeString:=False)> _
Public Function Test(WebInfo As GetUserID) As Person
Dim Someone As New Person
Someone.Name = "Bob"
Someone.FavoriteColor = "Green"
Someone.ID = WebInfo.WebUserID.ToString()
Return Someone
End Function
The Web Client (set up to be send and receive JSON)
public Person Test(int UserID, string url) {
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url + "test.asmx/Test");
webRequest.Method = "POST";
webRequest.ContentType = "application/json; charset=utf-8";
StreamWriter sw = new StreamWriter(webRequest.GetRequestStream());
sw.Write("{'WebInfo':{'WebUserID':1}}"); // this works from JQuery
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Person));
Person someone = (Person)jsonSerializer.ReadObject(responseStream);
return someone;
}
Has anyone out there done this successfully?
Thanks

Here is a method that makes calls to a JSON web service, allowing the developer to both send and receive complext data types. The object passed in can be any data type or class. The result is a JSON string, and or any error message the methods type is shown below
public class WebServiceCallReturn {
public string JSONResponse { get; set; }
public string SimpleResponse { get; set; }
public string Error { get; set; }
}
public WebServiceCallReturn WebServiceJSONCall(string uri, string requestType, object postData = null) {
WebServiceCallReturn result = new WebServiceCallReturn();
// create request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.Method = requestType;
webRequest.Accept = "application/json; charset=utf-8";
// add json data object to send
if (requestType == "POST") {
string json = "{ }";
if (postData != null) {
try { // the serializer is fairly robust when used this way
DataContractJsonSerializer ser = new DataContractJsonSerializer(postData.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, postData);
json = Encoding.UTF8.GetString(ms.ToArray());
} catch {
result.Error = "Error serializing post";
}
}
webRequest.ContentLength = json.Length;
StreamWriter sw;
try {
sw = new StreamWriter(webRequest.GetRequestStream());
} catch (Exception ex) {
// the remote name could not be resolved
result.Error = ex.Message;
return result;
}
sw.Write(json);
sw.Close();
}
// read response
HttpWebResponse webResponse;
try {
webResponse = (HttpWebResponse)webRequest.GetResponse();
} catch (Exception ex) {
// The remote server returned an error...
// (400) Bad Request
// (403) Access forbidden (check the application pool)
// (404) Not Found
// (405) Method not allowed
// (415) ...not the expected type
// (500) Internal Server Error (problem with IIS or unhandled error in web service)
result.Error = ex.Message;
return result;
}
Stream responseStream = webResponse.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
string resultString = sr.ReadToEnd();
sr.Close();
responseStream.Close();
result.JSONResponse = resultString;
return result;
}
This method could be used as follows
public SomeCustomDataClass Getsomeinformation(int userID) {
UserInfoClass postData = new UserInfoClass();
postData.WebUserID = userID;
SomeCustomDataClass result = new SomeCustomDataClass();
string uri = URL + "SomeServices.svc/GetSomething";
WebServiceCallReturn webReturn = WebServiceJSONCall(uri, "POST", postData);
if (webReturn.Error == null) {
//resultString = CleanJSON(resultString);
JavaScriptSerializer serializer = new JavaScriptSerializer();
try {
result = serializer.Deserialize<SomeCustomDataClass>(webReturn.JSONResponse);
} catch {
result.Error = "Error deserializing";
}
} else {
result.Error = webReturn.Error;
}
return result;
}
Hope that helps someone

Related

How to upload json data using webclient to a custom class post method in VB.net?

I'm trying to upload Json data via WebClient to my web service post method, which is getting the body parameter as custom class variable.
I'm getting 404 error when I post the request. Looking for help to send this post data successfully to my web service.
I tried to send the post request like below
Dim webclient As New WebClient()
Dim reqString As Byte()
Dim resByte As Byte()
Dim sendMessage As Object
sendMessage = New With {Key .chatID = "***********", .messageText = "test"}
webclient.Headers("content-type") = "application/json"
webclient.Headers("accept") = "text/plain"
reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(sendMessage))
resByte = webclient.UploadData("http://testurl/SendMessage", "post", reqString)
...
This is my web service method
...
[HttpPost("/SendMessage")]
public string SendMessage([FromBody] SendMessage sendMessage)
{
string apiToken = "*******************************************";
string urlString = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}";
string messageText = sendMessage.messageText;
string chatId = sendMessage.chatID;
urlString = String.Format(urlString, apiToken, chatId, messageText);
try
{
WebRequest request = WebRequest.Create(urlString);
WebResponse response = request.GetResponse();
string responseStatus = ((HttpWebResponse)response).StatusDescription;
if (responseStatus == "OK")
{
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
using (StreamReader reader = new StreamReader(dataStream))
{
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Check the content.
if (responseFromServer.Contains("\"ok\":true"))
{
// Display a confirmation.
return ("Message text was successfully sent to Telegram :-)");
}
else
{
// Display an error.
return ("Failed to send the message text to Telegram :-(");
}
// Display the content.
return (responseFromServer);
}
}
}
else
{
// Display an error.
return ("Failed to send the message text to Telegram :-(");
return ("Response status: " + responseStatus);
}
// Close the response.
response.Close();
//Console.ReadKey();
}
catch (Exception ex)
{
// Display an error.
return ("Failed to send the message text to Telegram :-(");
return (ex.ToString());
}
}
...
This is my custom class
public class SendMessage
{
public string chatID { get; set; }
public string messageText { get; set; }
}

Odata naming file return error message of the

I have this custom Odata function to download pdf from download pdf database. I have some issues
1.with Pdf name does not name "reportname.pdf" it is named response.pdf as
2.return error message of reportBinary is null
[HttpGet]
[ODataRoute("GetDownloadReport(downloadId={downloadId})")]
public HttpResponseMessage GetDownloadReport(Guid downloadId)
var received = DateTime.UtcNow;
byte[] reportBinary = null;
string queryString = "SELECT report FROM downloads WHERE id = #downloadId ";
bool success = false;
using (SqlConnection conn = new SqlConnection(connectionString))
{
//get the binary from database
}
HttpResponseMessage response = null;
try
{
if (reportBinary == null)
return Request.CreateResponse(HttpStatusCode.Gone);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(reportBinary);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = "PORTName.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
}
try to set filename manually:
String headerInfo = "attachment; filename=" + System.Web.HttpUtility.UrlPathEncode("PORTName.pdf");
response.Content.Headers.Add("Content-Disposition", headerInfo);
I'm not sure what do you want to do about error message, but if you mean setting string content, just set it ;)
response = Request.CreateResponse(HttpStatusCode.Gone);
response.Content = new StringContent(...);
return response;
Consider using NotFound instead of Gone status code (Gone has very specific meaning).

Created a Soap Webservice and calling it in asp.net uisng code and getting error of The remote name could not be resolved

I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?

The remote server returned an error: (400) Bad Request. When try to login with facebook in asp.net

I am try to login with a user with Facebook account in my website, but the applcation gives me error that The remote server returned an error: (400) Bad Request.
Below is my code:
public string WebRequest(Method method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "[You user agent]";
webRequest.Timeout = 50000;
if (method == Method.POST)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
*It gives me error in this method:*
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
Ooo been a while since Iv'e played with webRequest but I think your problem might be
webRequest.GetResponse().GetResponseStream().Close();
in the finally block. Since you've already called
webRequest.GetResponse().GetResponseStream()
in the body of try block. Documentation states:
The GetResponse method sends a request to an Internet resource and
returns a WebResponse instance. If the request has already been
initiated by a call to GetRequestStream, the GetResponse method
completes the request and returns any response.
Therefore as I read it, the response had already been returned in the try block and then when you call it again in the finally block, it fails...since it's already been retrieved. Just comment out that line and see how you go. The StreamReader should close the underlying connection when you close it.
So try:
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
responseReader.Close();
}
return responseData;
}

Tomcat returns http response code 400

I was googling for a long time, but still can't find a solution to my case.
My Tomcat sometimes returns an exception :
Error in postRequest(): Server returned HTTP response code: 400 for URL: http://localhost:80/CITIUS2/webresources/entities.personainterna/
Sometimes it works and sometimes it returns this exception, so I really don't know what is the reason...
Connection function:
public static String excutePost(String targetURL, String urlParameters) throws UnsupportedEncodingException {
URL url;
HttpURLConnection connection = null;
String responseXML = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
byte[] requestXML = urlParameters.getBytes();
connection.setRequestProperty("Content-Length", String.valueOf(requestXML.length));
connection.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
// Send the String that was read into postByte.
OutputStream out = connection.getOutputStream();
out.write(requestXML);
out.close();
// Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
String temp;
String tempResponse = "";
//Create a string using response from web services
while ((temp = br.readLine()) != null) {
tempResponse = tempResponse + temp;
}
responseXML = tempResponse;
br.close();
isr.close();
} catch (java.net.MalformedURLException e) {
System.out.println("Error in postRequest(): Secure Service Required");
} catch (Exception e) {
System.out.println("Error in postRequest(): " + e.getMessage());
}
return responseXML;
}
# Edit:
In general build is successful, there are no errors, only this one in the Apache Tomcat's output window.
Rest method:
#POST
#Consumes({"application/xml", "application/json"})
public Response create(Personainterna entity) {
try {
getJpaController().create(entity);
return Response.created(URI.create(entity.getPersonaId().toString())).build();
} catch (Exception ex) {
return Response.notModified(ex.getMessage()).build();
}
}

Resources