I am trying to get a result from a webservice in an ASP.NET MVC (3) app. The webservice call (see below) works perfectly and I can see in Fiddler that I get a proper SOAP result back.
However, the call to "client.requestAuthorisation" results in a null. Am I missing something?
public static string GetToken()
{
var token = "";
var username = "user";
var password = "pass";
using (var client = new MvcApplication1.TheWebService.SingleSignOnSoapServerPortTypeClient())
{
using (new System.ServiceModel.OperationContextScope(client.InnerChannel))
{
var httpRequestProperty = new System.ServiceModel.Channels.HttpRequestMessageProperty();
var authenticationString = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password)));
httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = string.Format("Basic {0}", authenticationString);
System.ServiceModel.OperationContext.Current.OutgoingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name] = httpRequestProperty;
token = client.requestAuthorisation("admin");
}
}
return token;
}
The returned SOAP message is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="https://www.somedomain.ext" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:requestAuthorisationResponse>
<return xsi:type="xsd:string">6389a2dd8da662130e6ad1997267c67b043adc21</return>
</ns1:requestAuthorisationResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Have you tried regenerating the client code?
Related
I have XML Web API like this
http://test/REST?hiInstanceId=7
XML parameters
<request_info>SALE</request_info><location_id>36</location_id>
<from_dt>01-JUN-22</from_dt><to_dt>10-JUN-22</to_dt>
how to get the response from the XML web API?
how to get response from the xml web Api
To make the Asp.net Core API return the XML format response. We need to configure XML formatters implemented using XmlSerializer, call AddXmlSerializerFormatters:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.AddXmlSerializerFormatters();
Then, in the API controller, use the [Produces] attribute to specify a format.
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpGet]
[Produces("application/xml")]
public TestModel GetCustomers( )
{
return new TestModel()
{
request_info = "Sale",
location_id = 36,
from_dt = "01-JUN-22",
to_dt = "10-JUN-22"
};
}
}
Then, use the following code to call the API method and get the XML response:
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://localhost:44374/api/todo"));
httpRequest.ContentType = "application/xml";
httpRequest.Method = "Get";
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream stream = httpResponse.GetResponseStream())
{
string xml = (new StreamReader(stream)).ReadToEnd(); //get the XML response
//Using XMLSerializer to convert the XML response to the object.
XmlSerializer serializer = new XmlSerializer(typeof(TestModel));
StringReader rdr = new StringReader(xml);
var result = (TestModel)serializer.Deserialize(rdr);
}
}
The debug screenshot like this:
I am trying to develop twitter client. i am using RestSharp for api. its work fine with authentication and gettimeline but its give error when i try to search twitter with # hashtag . its gives error like bad request and unauthorized.
Working code
public string GetTimeLine(string key,string secret,string userToken,string userSecret)
{
var request = new RestRequest("/1.1/statuses/user_timeline.json", Method.GET);
Client.Authenticator = OAuth1Authenticator.ForProtectedResource(key, secret, userToken, userSecret);
var response = Client.Execute(request);
return response.Content;
}
Respond with unauthorized error:
public string GetHashtag(string key, string secret, string userToken, string userSecret)
{
var request = new RestRequest("/1.1/search/tweets.json?q=%23freebandnames", Method.GET);
Client.Authenticator = OAuth1Authenticator.ForProtectedResource(key, secret, userToken, userSecret);
var response = Client.Execute(request);
return response.Content;
}
Try this:
var request = new RestRequest("/1.1/search/tweets.json?q={query}", Method.GET);
request.AddUrlSegment("query", "#freebandnames");
There is a php application which will read the result from the web service i have created.
The xml response they want is like
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header />
<s:Body>
<WorkResponse xmlns="http://tempuri.org/">
<WorkResult>Name<WorkResult>
<WorkResult>Occupation<WorkResult>
</WorkResult>
</WorkResponse>
</s:Body>
But my method return like this `
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header />
<s:Body>
<WorkResponse xmlns="http://tempuri.org/">
<WorkResult xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:string>Name</a:string>
<a:string>Occupation</a:string>
</WorkResult>
</WorkResponse>
</s:Body>`
And below is the method I have written in the web service
public string[] Work()
{
string[] request = new String[2];
request[0] = "Name";
request[1] = "Occupation";
return request;
}
How can I do to get the result they want.
Please help me to come out of this issue
If you need WorkResult node to contain both "Name" and "Occupation" and at the same level in the xml, you can achieve it returning a List in your WebMethod Work(). Here is an example:
public List<String> Work()
{
public List<String> result = new List<String>();
result.Add("Name");
result.Add("Occupation");
return result;
}
I am trying to create a file upload in a flex/air application that sends information to a .NET wcf SOAP webservice. The file upload also has to have progress indicating events. The service uses a Stream as a MessageBodyMember to allow streaming upload. My input looks a little like this:
[MessageContract]
public class SendFileRequestMessage : IDisposable
{
public string UserName;
[MessageBodyMember(Order = 1)]
public Stream FileData;
}
and the service looks like this:
public interface IFileTransferService
{
[OperationContract]
SendFileResponseMessage SendFile(SendFileRequestMessage request);
}
Now when i create a proxy class in VS2010 i get a Stream object for FileData. If I do the same in Flash Builder 4.7 the FileData is interpreted as a ByteArray. I already looked into FileUpload and UrlLoader in my client but i can't get the body member set. My action script now looks like this
not working
var dataToSave:XML = <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q0="http://mystuff/uploadservice/v1"><soapenv:Body><q0:SendFile/></soapenv:Body></soapenv:Envelope>
var request:URLRequest = new URLRequest("http://localhost:31454/Uploadhandler.svc");
request.requestHeaders = new Array(new URLRequestHeader("SOAPAction", "http://mystuff/uploadservice/v1/IFileTransferService/SendFile"));
request.data = dataToSave;
request.contentType = "text/xml; charset=utf-8";
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(request);
So how can do a streaming file upload to a soap service from flex? Any help would be very appreciated.
I'm not familiar with .NET SOAP model, but if it expects standard http content dispositions for file data you can try getting FileReference object for your file and then pass your URLRequiest in its upload method. In your case this could be like
... Create class level variable ...
var fr:FileReference = new FileReference();
... Obtain file reference somewhere ...
//Set handlers for Filereference events
fr.browse(); //Obtain actual file reference
... Somewhere in selectHandler chain....
var dataToSave:XML = <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q0="http://mystuff/uploadservice/v1"><soapenv:Body><q0:SendFile/></soapenv:Body></soapenv:Envelope>
var request:URLRequest = new URLRequest("http://localhost:31454/Uploadhandler.svc");
request.requestHeaders = new Array(new URLRequestHeader("SOAPAction", "http://mystuff/uploadservice/v1/IFileTransferService/SendFile"));
request.data = dataToSave;
request.contentType = "text/xml; charset=utf-8";
request.method = URLRequestMethod.POST;
//Do POST
fr.upload(request);
This Documentation contains examples for using FileReference.
Am using simple webservice ".asmx".In my web service returning some data like:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://tempuri.org/">
{"Table":[{"minlatency":16.0,"Time":"\/Date(1328248782660+0530)\/"},{"minlatency":7.0,"Time":"\/Date(1328248784677+0530)\/"},{"minlatency":13.0,"Time":"\/Date(1328248786690+0530)\/"},{"minlatency":6.0,"Time":"\/Date(1328248788690+0530)\/"},{"minlatency":20.0,"Time":"\/Date(1328248790707+0530)\/"}]}</string>
I am using:
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
after [webmethod]in my service,and it is giving error in ajax callback,i want return values in json format.
I had the same issue a few weeks ago, I found that using the following as my service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetPointers() {
DataTable dtmkrs = new DataTable();
dtmkrs.Load(SPs.GetPointers().GetReader());
string[][] pointerArray = new string[dtmkrs.Rows.Count][];
int i = 0;
foreach (DataRow mkrs in dtmkrs.Rows)
{
pointerArray[i] = new string[] { mkrs["LocationID"].ToString(), mkrs["Title"].ToString(), mkrs["Blurb"].ToString(), mkrs["Url"].ToString(), mkrs["LongLatPoint"].ToString() };
i++;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(pointerArray);
dtmkrs.Dispose();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Flush();
Context.Response.Write(strJSON);
}
and the following javascript (using mootools)
new Request.JSON({
url:<url to webservice>,
method: 'GET',
onSuccess: function(resJson, respText) {
jsonResponse = resJson;
dropJSON();
}
}).send();
the previous is a function for getting Googlemaps markers from an SQL server database in ASP.NET c#
I have a service returning JSON which I call from jQuery and it only returns pure JSON. This is how I have the interface defined:
<OperationContract()>
<WebInvoke(Method:="POST", BodyStyle:=WebMessageBodyStyle.Wrapped, ResponseFormat:=WebMessageFormat.Json)>
Function GetNotes() As List(Of MyClassObject)
you can fix it using what [Ira Rainy] has suggested, or use attributes to do the same job.
using attributes, simply put the following line above your desired method(s):
[WebInvokeAttribute(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
public string DoSomething()
{
// your code here
}
Hope this will fix your problem.