The remote server returned an error: (500) Internal Server Error. web service error soap request - asp.net

I want to create a web service that responds to soap requests. and returns a soap response.now i want to send 2 parameters to the service namely invoiceno and orderno do something with it at the webservice and return the result. currently im just trying to retuen the values recieved as it is back to the client, but i keep getting this error "The remote server returned an error: (500) Internal Server Error." I am a total novice with soap web services. please tell me what i am doing wrong. or is this completely wrong.
namespace WebApplication7
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public XmlDocument savedata()
{
XmlDocument xmlSoapRequest = new XmlDocument();
Stream receiveStream = HttpContext.Current.Request.InputStream;
receiveStream.Position = 0;
string invoiceno2 = xmlSoapRequest.GetElementById("invoiceno").Value;
string orderno2 = xmlSoapRequest.GetElementById("orderno").Value;
string gg = #" <soap:Envelopexmlns:soap=""http://www.w3.org/2001/12/soap-envelope""soap:encodingStyle=""http://www.w3.org/2001/12/soap-encoding"">
<soap:Body xmlns:m=""http://www.example.org/stock"">
<m:savedata>
<m:invoiceno>" + invoiceno2 + #"</m:invoiceno>
<m:orderno>" + orderno2 + #"</m:orderno>
<m:haha>hahahahahahahha</m:haha>
</m:savedata>
</soap:Body>
</soap:Envelope>";
XmlDocument cv = new XmlDocument();
cv.LoadXml(gg);
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
// Load into XML document
xmlSoapRequest.Load(readStream);
}
// string gg = invoiceno + " hahahahaha " + orderno;
return cv;
}
}
}
and this is the client i created to consume it
namespace unicommerce_testing
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Execute());
}
public static string Execute()
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(CreateOrEditItemTypeRequestCreator("44", "2500313-125","Watch",20,20,20,56,"This is a test product","Red","Brillier","NA",45000));
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
return soapResult;
}
}
}
/// <summary>
/// Create a soap webrequest to [Url]
/// </summary>
/// <returns></returns>
public static HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(#"http://localhost:1234/test/WebService1.asmx/savedata");
webRequest.Headers.Add(#"SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
public static string CreateOrEditItemTypeRequestCreator()
{
string request= #"<soap:Envelopexmlns:soap=""http://www.w3.org/2001/12/soap-envelope""soap:encodingStyle=""http://www.w3.org/2001/12/soap-encoding"">
<soap:Body xmlns:m=""http://www.example.org/stock"">
<m:savedata>
<m:invoiceno>inv1</m:invoiceno>
<m:orderno>od1</m:orderno>
</m:savedata>
</soap:Body>
</soap:Envelope>";
return request;
}
}
}

Related

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?

getting directed to ASP.NET home page on browser

I am trying to run the following HTTP POST API Call using ASP.NET on Visual studio 2013. I created a new web application project as mentioned here
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateNewAPICall("test api abc");
}
private object CreateNewAPICall(string apiDesc)
{
object result = null;
var accessKey = "myaccesskey";
var secretKey = "mysecretkey";
var uRLapiList = "http://myurl.com";
byte[] bytes = Encoding.UTF8.GetBytes("apiListDesc=" + apiDesc);
var method = "POST";
var timeString = DateTime.UtcNow.GetDateTimeFormats()[104];
var signature = GetSignature(secretKey, method, timeString);
var authorization = accessKey + ":" + signature;
HttpWebRequest request = CreateWebRequest(uRLapiList, "POST", bytes.Length, timeString, authorization);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseReader = new StreamReader(request.GetResponse().GetResponseStream());
// Return List api Data
result = responseReader.ReadToEnd();
}
}
return result;
}
private HttpWebRequest CreateWebRequest(string endPoint, string method, Int32 contentLength, string timeString, string authorization)
{
// Some code here
}
private string GetSignature(string secretKey, string method, string timeString)
{
// Some code here
}
private byte[] HMAC_SHA1(string signKey, string signMessage)
{
// Some code here
}
private string CreateSignature(string stringIn, string scretKey)
{
// Some code here
}
}
Right now, I am confused as to where to put this file in the "Solution Explorer" in order to
run the file and get the output on my browser?
Right now I have this code inside "Models-->Class1.cs" directory as shown in the image below:
So, when I press F-5 key, I am getting directed to the home page of the ASP.NET with the URL http://localhost:4439/
Do I need to make any changes here?

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

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

IISHandler error does not implement interface member 'System.Web.IHttpHandler.IsReusable',

How do i fix this error
Error 3 'FMMadminModule.IISHandler1' does not implement interface member 'System.Web.IHttpHandler.IsReusable',
Error 4 'FMMadminModule.IISHandler1' does not implement interface member 'System.Web.IHttpHandler.ProcessRequest(System.Web.HttpContext)'
Here is my handler
`using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.SessionState;
namespace FMMadminModule
{
public class IISHandler1 : IHttpHandler
{
/// <summary>
/// You will need to configure this handler in the web.config file of your
/// web and register it with IIS before being able to use it. For more information
/// see the following link: http://go.microsoft.com/?linkid=8101007
DataTable dt;
int key;
byte[] imageOut;
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
key = Convert.ToInt32(request.QueryString["Ind"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
}
You've declared a class twice. Remove the IISHandler1 class at the top, resulting in this:
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.SessionState;
namespace FMMadminModule
{
/// <summary>
/// You will need to configure this handler in the web.config file of your
/// web and register it with IIS before being able to use it. For more information
/// see the following link: http://go.microsoft.com/?linkid=8101007
public class imageHandler : IHttpHandler, IReadOnlySessionState
{
DataTable dt;
int key;
byte[] imageOut;
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
key = Convert.ToInt32(request.QueryString["Ind"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
You have nested two classes. Try removing one of the nestings:
public class imageHandler : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
int key = Convert.ToInt32(request.QueryString["Ind"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
DataTable dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
byte[] imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

authentication for a Web service options

I am new to Web services and .NET.
I have to authenticate a web service that is being accessed using http post.
I tried putting a custom soap header and sending it to the service and checking the header in service but the header object is always null in the service.
also if i put the user and password options in http headers how can i validate them on the server ?
Thanks in advance
Client code:
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request;
string strSOAPRequestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
"<soap:Header>"+
"<AuthHeader xmlns=\"http://tempuri.org/\">" +
"<Username>apple</Username>"+
"<Password>apple</Password>"+
"</AuthHeader>"+
"</soap:Header>"+
"<soap:Body xmlns=\"http://tempuri.org/\">"+
"<HelloWorld>"+
"</soap:Body>"+
"</soap:Envelope>";
request = (HttpWebRequest)WebRequest.Create("http://localhost:1494/Service1.asmx/HelloWorld");
request.Accept = "text/xml";
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
request.ContentLength = strSOAPRequestBody.Length;
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(strSOAPRequestBody);
sw.Flush();
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
{
txtResponse.Text = System.Web.HttpUtility.HtmlDecode(responseStream.ReadToEnd());
}
}
}
Service
public class Service1 : System.Web.Services.WebService
{
public AuthHeader Authentication;
[WebMethod]
[SoapHeader("Authentication", Direction = SoapHeaderDirection.In)]
public XmlDocument HelloWorld()
{
XmlDocument response = new XmlDocument();
try
{
//Boolean validateUser = Membership.ValidateUser(Authentication.Username, Authentication.Password);
if (Authentication != null)
{
response.LoadXml(String.Format("{0}{1}{2}", "<BOM>", "Hurray", "</BOM>"));
}
}
catch( Exception ex)
{
response.LoadXml(String.Format("{0}{1}{2}", "<Error>", ex.Message, "</Error>"));
}
return response;
}
}
The problem is with the client code:
Set the URI to the service URI (i.e. the asmx file)
Add the soap action as a header (i.e. HelloWorld)
Set the content type as text/xml
Change the soap request to include the namespace on the soap method and not the body element
Try this:
HttpWebRequest request;
string strSOAPRequestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
" <soap:Header>" +
" <AuthHeader xmlns=\"http://tempuri.org/\">" +
" <Username>string</Username>" +
" <Password>string</Password>" +
" </AuthHeader>" +
" </soap:Header>" +
" <soap:Body>" +
" <HelloWorld xmlns=\"http://tempuri.org/\" />" +
" </soap:Body>" +
"</soap:Envelope>";
request = (HttpWebRequest)WebRequest.Create("http://localhost:1494/Service1.asmx");
request.Accept = "text/xml";
request.Method = "POST";
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Headers.Add("SOAPAction", "\"http://tempuri.org/HelloWorld\"");
request.ContentLength = strSOAPRequestBody.Length;
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(strSOAPRequestBody);
sw.Flush();
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine((responseStream.ReadToEnd()));
}
}
If you do that you should receive the response:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3
.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body><HelloWorldResponse xmlns="http://tempuri.org/">
<HelloWorldResult>
<BOM xmlns="">Hurray</BOM>
</HelloWorldResult>
</HelloWorldResponse>
</soap:Body>
</soap:Envelope>
To validate the username and password would depend on your implementation -- if you have asp.net membership then you should be able to use the ValidateUser method. Also note that if you are not using SSL then the username and password will be visible when sent over the wire.
Another note is that hand crafting XML as a string is almost always a bad idea so (at the very least) use XML framework classes to generate proper XML. Even better is to use web service toolkit.

Resources