I am creating ASMX web service in .Net for javaclient. Provided soap looks like this
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pus="http://www.example.org/pusheventservice/">
<soapenv:Header>
<ServiceHeader>
<TransactionID>258350</TransactionID>
<TransactionDate>2014/12/21</TransactionDate>.......
and javaclient expects response SOAP
like this
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pus="http://www.example.org/pusheventservice/">
<soapenv:Header>
<ResponseServiceHeader>
<TransactionID>258350</TransactionID>
<TransactionDate>2014/12/21</TransactionDate>....
means requestElement is 'ServiceHeader' and ResponseElement must be 'ResponseServiceHeader'
I WebMethod i achieved this but unable in Header.
Is it Possible?? If Yes how?? Also I Cant use WCF....
EDITS
namespace PushWS
{
[WebService(Namespace = "http://localhost:60463/PushEvent.asmx")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[SoapDocumentService(SoapBindingUse.Literal, SoapParameterStyle.Bare, RoutingStyle = SoapServiceRoutingStyle.SoapAction)]
// 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 PushEvent : System.Web.Services.WebService
{
public ServiceHeader serviceHeader = null;
public SoapUnknownHeader[] userCredentials;
[WebMethod(Description = "updateEvent receives XML from Client")]
[SoapHeader("serviceHeader", Direction = SoapHeaderDirection.InOut)]
[SoapHeader("userCredentials", Required = true)]
[return: XmlElement("EventResponse")]
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://localhost:60463/PushEvent.asmx/updateEvent",
RequestElementName = "updateEventRequest",
ResponseElementName = "updateEventResponse")]
public XmlElement updateEvent([XmlAnyElement]XmlElement MyPushEvent)
{
//Logic here
}
public class ServiceHeader : SoapHeader
{
public string TransactionID{get;set;}
public string TransactionDate{get;set;}
}
}
Create a derived class for the response header:
public class ResponseServiceHeader : ServiceHeader
{
}
public ServiceHeader serviceHeader = null;
public ResponseServiceHeader responseServiceHeader = null;
[SoapHeader("serviceHeader", Direction = SoapHeaderDirection.Int)]
[SoapHeader("responseServiceHeader", Direction = SoapHeaderDirection.Out)]
Related
I'm running a REST API service that has this action :
[HttpPost]
public FooResponse DoFoo(FooRequest request)
//public FooResponse DoFoo([FromBody] FooRequest request)
{
return null;
}
My request:
public class FooRequest
{
public string FooId;
}
I have an Angular client, that's making this call :
startFoo(fooId: string)
{
const url = `${this.baseUrl}StartFoo`;
const params = new HttpParams()
.set('FooId', fooId);
console.log(`params : ${params}`);
const result = this.httpClient.post<fooItem>(url, {params}).toPromise();
return result;
}
When I make the call from PostMan, the FooId is populated, when I call it from Angular, the endpoint is hit, but the param is always null. When I look in the console log, the parameters is there.
I've tried this solution, but it did not resolve my issue.
What am I missing?
You should add [FromBody] attribute in method .
[HttpPost]
public FooResponse DoFoo([FromBody] FooRequest request)
{
return null;
}
While you send the request to api, your request body must be in json format.
var fooRequest = { FooId : 1};
const result = this.httpClient.post<fooItem>(url, JSON.stringify(fooRequest) ).toPromise();
I did not try, I guess that It will work.
I'm trying to add this Header class to my SOAP request but can't see how. The Header class was given to me as part of the implementation but there's no instructions on how to use it and I'm a bit stuck - I've not used WSDL and web services before. I'm sure the answer must be blindingly easy but I just can't see it.
Header Requirements
<soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-19" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsse:Username>##USERNAME##</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">##PASSWORD##</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
Header class
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
namespace Consuming
{
public class SecurityHeader : MessageHeader
{
private readonly UsernameToken _usernameToken;
public SecurityHeader(string id, string username, string password)
{
_usernameToken = new UsernameToken(id, username, password);
}
public override string Name
{
get { return "Security"; }
}
public override string Namespace
{
get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
serializer.Serialize(writer, _usernameToken);
}
}
[XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
public class UsernameToken
{
public UsernameToken()
{
}
public UsernameToken(string id, string username, string password)
{
Id = id;
Username = username;
Password = new Password() { Value = password };
}
[XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
public string Id { get; set; }
[XmlElement]
public string Username { get; set; }
[XmlElement]
public Password Password { get; set; }
}
public class Password
{
public Password()
{
Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
}
[XmlAttribute]
public string Type { get; set; }
[XmlText]
public string Value { get; set; }
}
}
Code
var mySoapHeader = new SecurityHeader("ID","Username","password");
var client = new GroupWebServiceClient(); // Created from Add Web Reference
client.?????? = mySoapHeader;// I can't see how to add the Header to the request
var response = new groupNameListV1();
response = client.getAllDescendants("6335");//This needs the header - omitting gives "An error was discovered processing the <wsse:Security> header"
EDIT
I figured it out in the end, turns out it was pretty easy - Adding the solution in case anyone else finds it useful
using (new OperationContextScope(client.InnerChannel))
{
OperationContext.Current.OutgoingMessageHeaders.Add(
new SecurityHeader("ID", "USER", "PWD"));
var response = new groupNameListV1();
response = client.getAllDescendants("cng_so_6553");
//other code
}
Generally you need to add behavior extension.
Create a class that implements IClientMessageInspector. In the BeforeSendRequest method, add your custom header to the outgoing message. It might look something like this:
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
{
httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}
Then create an endpoint behavior that applies the message inspector to the client runtime. You can apply the behavior via an attribute or via configuration using a behavior extension element.
Here is a example of how to add an HTTP user-agent header to all request messages. I used this in a few of my clients.
Is this what you had in mind?
I am having a problem deserializing json in my rest self-hosted service.
I have a test page that invokes the self-hosted REST with JSON, here is the code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
function doFunction() {
xhr = new XMLHttpRequest();
var url = "https://localhost:1234/business/test/testing2/endpoint";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
alert(json);
}
}
var data = JSON.stringify({ testing : "test" });
xhr.send(data);
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
</div>
</form>
</body>
</html>
And here is the interface and contracts of my self-hosted service:
[DataContract]
public class OperationInput
{
[DataMember]
public string testing { get; set; }
}
[DataContract]
public class OperationOutput
{
[DataMember]
public int Status { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public string AddInfo { get; set; }
[DataMember]
public string PartnerID { get; set; }
[DataMember]
public string SessionID { get; set; }
}
[ServiceContract]
interface IRegisterOperation
{
[OperationContract]
[WebInvoke(UriTemplate = "/endpoint",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "*")]
OperationOutput Operation(OperationInput order);
}
And here is the implementation of the interface:
public class RegisterOperation : IRegisterOperation
{
public OperationOutput Operation(OperationInput input)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\testing.txt", false);
file.WriteLine(input.testing);
file.Close();
OperationOutput output = new OperationOutput();
output.Status = 200;
output.Message = "The action has been successfully recorded on NAVe";
output.AddInfo = "";
return output;
}
}
I am creating the self-host using this code:
host = new ServiceHost(implementationType, baseAddress);
ServiceEndpoint se = host.AddServiceEndpoint(endpointType, new WebHttpBinding(WebHttpSecurityMode.Transport), "");
se.Behaviors.Add(new WebHttpBehavior());
host.Open();
Using debug I notice that it hits the breakpoint inside my service, so the call to localhost is working but the parameter of input is null, as you can see in the image below:
Here is 2 images capturing the POST Request with JSON on fiddler:
Have you any idea why I am getting null ? instead of the string "test" as I do on the invocation in javascript?
Thank you very much in advance ;)
EDIT:
I activated HTTPS Decryption on Fiddler and now pressed "Yes" to install certificate on trusted ca instead of pressin "no", and the breakpoint is hitted, and fiddler now captured an options request as the following images represent
Shouldn't this be a post request instead of a options request?? maybe that's why I don't see the json?
Thanks a lot
I figured it out, the problem was the OPTIONS Request, I need to receive a POST Request so I get the JSON.
I added a behaviour attribute to my service host so that it responds to options request allowing the wcf service host to receive cross origin requests.
So I added the code from the answer of this (Cross Origin Resource Sharing for c# WCF Restful web service hosted as Windows service) question and now I get a POST Request after the first Options request:
If the link is no longer available, here is the solution of the question:
CODE:
Create 2 classes as follows:
MessageInspector implementing IDispatchMessageInspector.
BehaviorAttribute implementing Attribute, IEndpointBehavior and IOperationBehavior.
With the following details:
//MessageInspector Class
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Description;
namespace myCorsService
{
public class MessageInspector : IDispatchMessageInspector
{
private ServiceEndpoint _serviceEndpoint;
public MessageInspector(ServiceEndpoint serviceEndpoint)
{
_serviceEndpoint = serviceEndpoint;
}
/// <summary>
/// Called when an inbound message been received
/// </summary>
/// <param name="request">The request message.</param>
/// <param name="channel">The incoming channel.</param>
/// <param name="instanceContext">The current service instance.</param>
/// <returns>
/// The object used to correlate stateMsg.
/// This object is passed back in the method.
/// </returns>
public object AfterReceiveRequest(ref Message request,
IClientChannel channel,
InstanceContext instanceContext)
{
StateMessage stateMsg = null;
HttpRequestMessageProperty requestProperty = null;
if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
requestProperty = request.Properties[HttpRequestMessageProperty.Name]
as HttpRequestMessageProperty;
}
if (requestProperty != null)
{
var origin = requestProperty.Headers["Origin"];
if (!string.IsNullOrEmpty(origin))
{
stateMsg = new StateMessage();
// if a cors options request (preflight) is detected,
// we create our own reply message and don't invoke any
// operation at all.
if (requestProperty.Method == "OPTIONS")
{
stateMsg.Message = Message.CreateMessage(request.Version, null);
}
request.Properties.Add("CrossOriginResourceSharingState", stateMsg);
}
}
return stateMsg;
}
/// <summary>
/// Called after the operation has returned but before the reply message
/// is sent.
/// </summary>
/// <param name="reply">The reply message. This value is null if the
/// operation is one way.</param>
/// <param name="correlationState">The correlation object returned from
/// the method.</param>
public void BeforeSendReply(ref Message reply, object correlationState)
{
var stateMsg = correlationState as StateMessage;
if (stateMsg != null)
{
if (stateMsg.Message != null)
{
reply = stateMsg.Message;
}
HttpResponseMessageProperty responseProperty = null;
if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
{
responseProperty = reply.Properties[HttpResponseMessageProperty.Name]
as HttpResponseMessageProperty;
}
if (responseProperty == null)
{
responseProperty = new HttpResponseMessageProperty();
reply.Properties.Add(HttpResponseMessageProperty.Name,
responseProperty);
}
// Access-Control-Allow-Origin should be added for all cors responses
responseProperty.Headers.Set("Access-Control-Allow-Origin", "*");
if (stateMsg.Message != null)
{
// the following headers should only be added for OPTIONS requests
responseProperty.Headers.Set("Access-Control-Allow-Methods",
"POST, OPTIONS, GET");
responseProperty.Headers.Set("Access-Control-Allow-Headers",
"Content-Type, Accept, Authorization, x-requested-with");
}
}
}
}
class StateMessage
{
public Message Message;
}
}
//BehaviorAttribute Class
using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
namespace OpenBetRetail.NFCReaderService
{
public class BehaviorAttribute : Attribute, IEndpointBehavior,
IOperationBehavior
{
public void Validate(ServiceEndpoint endpoint) { }
public void AddBindingParameters(ServiceEndpoint endpoint,
BindingParameterCollection bindingParameters) { }
/// <summary>
/// This service modify or extend the service across an endpoint.
/// </summary>
/// <param name="endpoint">The endpoint that exposes the contract.</param>
/// <param name="endpointDispatcher">The endpoint dispatcher to be
/// modified or extended.</param>
public void ApplyDispatchBehavior(ServiceEndpoint endpoint,
EndpointDispatcher endpointDispatcher)
{
// add inspector which detects cross origin requests
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
new MessageInspector(endpoint));
}
public void ApplyClientBehavior(ServiceEndpoint endpoint,
ClientRuntime clientRuntime) { }
public void Validate(OperationDescription operationDescription) { }
public void ApplyDispatchBehavior(OperationDescription operationDescription,
DispatchOperation dispatchOperation) { }
public void ApplyClientBehavior(OperationDescription operationDescription,
ClientOperation clientOperation) { }
public void AddBindingParameters(OperationDescription operationDescription,
BindingParameterCollection bindingParameters) { }
}
}
After this all you need to do is add this message inspector to service end point behavior.
ServiceHost host = new ServiceHost(typeof(myService), _baseAddress);
foreach (ServiceEndpoint EP in host.Description.Endpoints)
EP.Behaviors.Add(new BehaviorAttribute());
Thanks for everyone help ;)
You have Method = "*"
I would experiment with:
Method = "POST" ....
[ServiceContract]
interface IRegisterOperation
{
OperationOutput Operation(OperationInput order);
like so:
[OperationContract]
[WebInvoke(UriTemplate = "/registeroperation",
Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
OperationOutput Operation(OperationInput order);
APPEND:
Your json does not look right (from the screen shots)
I would expect something simple like:
{
"ACTPRDX": "test"
}
Can you do an "alert" right after you stringify the object?
And show the results?
But (in general)...if your json is messed up, the "auto voodoo" of the Wcf Service Method won't work.
.....
This might be nit-picky, but try this:
Note the capital "T" after the hyphen.
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
I just found this in my code:
var jsonObject = { ACTPRDX : "test" };
var whatToSendOverTheWire = JSON.stringify(jsonObject);
Try that.
As mentioned, your json is wrong. the fix is to figure out how its being screwed up.
You actually pass primitive instead of expected object
var data = JSON.stringify({ ACTPRDX : "test" });
The above data would work for method :
public XYZ Something(string ACTPRDX)
You should send object to your method like that
var obj= new Object();
obj.ACTPRDX = "test";
var data = JSON.stringify({ order: obj});
Also interface and implementation have different name for parameter OperationInput -> order and input.
I use the android Ksoap2 library to build my App.
I want use this Library to send complex type request to my C# WebService.
How to receive this request? Define Class?
Thanks very much!
android code:
private Runnable SendComplexRequest = new Runnable() {
#Override
public void run() {
String MemberLogin_SOAP_ACTIONComplex = "http://tempuri.org/EchoStringMessage";
SoapObject request = new SoapObject(NAMESPACE, "EchoStringMessage");
SoapObject test1 = new SoapObject(NAMESPACE, "test1");
test1.addProperty("Name","Peter");
test1.addProperty("age","100");
request.addSoapObject(test1);
Log.v("ObjString",request.toString());
try
{
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE("http://XXX.XXX.XXX.XXX/MytestWeb/WebService1.asmx");
androidHttpTransport.call(MemberLogin_SOAP_ACTIONComplex, envelope);
Object object = envelope.getResponse();
response = object.toString();
Log.v("Receive Message",object.toString());
}
catch(Exception e)
{
Log.v("Error", e.getMessage());
}
}
};
And I get the Error and Log:
V/ObjString﹕ EchoStringMessage{test1{Name=Peter; age=100; }}
V/Error﹕ System.Web.Services.Protocols.SoapException:伺服器無法處理要求。
---> System.NullReferenceException:並未將物件參考設定為物件的執行個體。
C# WebService Code:
using ...
namespace WebServiceTest2
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string EchoStringMessage(object obj)
{
//do something
}
}
}
How do you add create a SOAP web service header?
Example
<soap:Header>
<myHeader xmlns="https://www.domain.com">
<Username>string</Username>
<Password>string</Password>
</myHeader>
</soap:Header>
source code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
namespace TestWebServices
{
/// <summary>
/// Summary description
/// </summary>
[WebService(Namespace = "https://Test.com")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Testing : System.Web.Services.WebService
{
[WebMethod]
public string GetTestValue()
{
return "xyz";
}
}
}
How about:
public class MyHeader : SoapHeader
{
public string Username;
public string Password;
}
There's more on the subject here:
Using SOAP Headers (MSDN - archived)
Defining and Processing SOAP Headers (MSDN)
If you need fine grain control over how the soap header xml gets rendered (happens when interfacing with a webservice written with java), you can always override all rendering by implementing IXmlSerializable
[XmlRoot("customHeader", Namespace = "http://somecompany.com/webservices/security/2012/topSecret")]
public class customHeader: SoapHeader, IXmlSerializable
{
public customHeader()
{
Actor = "http://schemas.xmlsoap.org/soap/actor/next";
MustUnderstand = false;
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
//throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
//throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("soap:actor", Actor);
writer.WriteAttributeString("soap:mustUnderstand", MustUnderstand ? "1" : "0");
writer.WriteRaw("some encrypted data");
//get it exactly the way you want it in here without mucking with Xml* property attributes for hours on end
//writer.WriteElement(...);
}
}
A SOAP message with headers may look something like the following:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<Username>string</Username>
<Password>string</Password>
</soap:Header>
</soap:Envelope>
EndpointAddressBuilder builder = new EndpointAddressBuilder(client.Endpoint.Address);
AddressHeader header = AddressHeader.CreateAddressHeader("apiKey", "http://tempuri.org", "longapikeyhere");
builder.Headers.Add(header);
client.Endpoint.Address = builder.ToEndpointAddress();