I am aware that there is a similar question here with no solution.
I'm working on a WCF streaming service over HTTP.
Here are my MessageContract
[MessageContract]
public class FileRequest
{
#region Message Header
[MessageHeader(MustUnderstand = true)]
public Credential Credentials { get; set; }
#endregion
#region Message body
[MessageBodyMember(Order = 1)]
public FileInfo FileInfo { get; set; }
#endregion
#region Ctor
// ...
#endregion
}
[MessageContract]
public class FileRequestResponse
{
#region Message Header
[MessageHeader(MustUnderstand = true)]
public FileInfo FileHeader { get; set; }
[MessageHeader(MustUnderstand = true)]
public OperationResult<bool> OperationResult { get; set; }
#endregion
#region Message Body
[MessageBodyMember]
public Stream FileStream { get; set; }
#endregion
#region Constructor
// ...
#endregion
}
Here is my ServiceContract
[ServiceContract(Namespace = "https://service.contract.example.com")]
public interface IUpdateService
{
[OperationContract(Action = "GetUpdates")]
OperationResult<List<FileInfo>> GetUpates(ApplicationInfo applicationInfo, Credential credential);
[OperationContract(Action = "GetFile")]
FileRequestResponse FileRequest(FileRequest fileRequest);
}
Now the question is why I am getting this error:
// CODEGEN: Generating message
contract since message FileRequest has
headers
When I add my service reference. The end result is that the service contract wraps the FileRequest operation into a wrapper which I do not want.
public FileInfo FileRequest(Credential Credentials, FileInfo, out OperationResult<bool> OperationResult, out System.IO.Stream FileStream)
NOTE:
I have not checked the "Always generate message contracts" in the service reference.
Set [MessageContract(IsWrapped=true)] for all the message contracts in the service and then try generating the proxy .
You might want to try to use the IsWrapped attribute on the message contract:
[MessageContract(IsWrapped=false)]
Not 100% sure which one you'll need (true or false) but that's one of the options you could try.
Also, another observation: I think it's a bit risky to have a method called FileRequest and a message contract which also is called FileRequest.
The generally accepted best practive would be to have a method GetFile, a request message for that called GetFileRequest and a response message type GetFileResponse. Do not use the same names for different things.
Related
I'm trying to port an existing Soap WebService to .NET5 but am having issue with overloading a Soap method parameter.
In NET4 the code looks like this
namespace SoapWebServiceeTest.Soap
{
/// <summary>
/// Summary description for WsgSPServiceOrderService
/// </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 TextWebService : System.Web.Services.WebService
{
[WebMethod]
public string Test(
[XmlElement("object1", typeof(Object1))]
[XmlElement("object2", typeof(Object2))]
[XmlElement("object3", typeof(Object3))]
object request)
{
return $"{request.GetType().Name}";
}
}
public class Object1 { public string Param1 { get; set; } }
public class Object2 { public string Param2 { get; set; } }
public class Object3 { public string Param3 { get; set; } }
}
How do I achieve this in .NET5?
I have tried following but got reflection exception: System.Reflection.AmbiguousMatchException: 'Multiple custom attributes of the same type found.'
[ServiceContract]
public interface ITestWebService
{
[OperationContract]
string Test(
[XmlElement("object1", typeof(Object1))]
[XmlElement("object2", typeof(Object2))]
[XmlElement("object3", typeof(Object3))]
object request);
}
And also tried this but VS Add Connected Services errored with "More than one message named 'ISampleService_Test_InputMessage' was specified. Each message must have a unique name."
[OperationContract]
string Test(Object1 request);
[OperationContract]
string Test(Object2 request);
Any help would be awesome
You may try this
You can make it post or get based on your need
[OperationContract]
[WebInvoke(UriTemplate = "Test1", Method = "POST"]
string Test(Object1 request);
and
[OperationContract]
[WebInvoke(UriTemplate = "Test2", Method = "POST"]
string Test(Object2 request);
This way you can achieve objective
Using VS2012 and NetTcpBinding. I am getting the following error when I call the serviceContract from the client - The service is hosted in IIS:
There was an error while trying to serialize parameter CS.ServiceContracts.Zzzzzz.Common:GetZipCodesResult. The InnerException message was 'Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.
Here is my ServiceContract:
[ServiceContract(SessionMode = SessionMode.Allowed, Namespace = "CS.ServiceContracts.Zzzzzz.Common",
Name = "IZzzzzzCommonService")]
public interface IZzzzzzCommonService
{
[OperationContract]
GetZipCodesResponse GetZipCodes(GetZipCodesRequest request);
}
Here is my DataContract:
[DataContract]
[Serializable]
public class GetZipCodesResponse : ResponseBase
{
[DataMember(IsRequired = true)]
public List<ZipCodes> ZipCodes { get; set; }
}
And here is the ResponseBase:
[DataContract]
[Serializable]
[KnownType(typeof(GetZipCodesResponse)), XmlInclude(typeof(GetZipCodesResponse))]
public class ResponseBase
{
[DataMember(IsRequired = true)]
public int ResponseCode { get; set; }
[DataMember(IsRequired = false)]
public int ReasonCode { get; set; }
[DataMember(IsRequired = false)]
public string ReasonText { get; set; }
}
Here is the Implementation of the serviceContract Interface:
public class ZzzzzzCommonService : IZzzzzzCommonService
{
public GetZipCodesResponse GetZipCodes(GetZipCodesRequest request)
{
var response = new GetZipCodesResponse();
try
{
response.ZipCodes = ZipCodes.GetCustom(request.ZipCode, request.City, request.State);
}
catch (Exception ex)
{
this.BuildExceptionResponse(response, ex);
}
return response; // I get to this line ok, but here is where the error occurs
}
}
And here is the client code where I am calling the Service:
public void ZipCodes()
{
var endPoint = new EndpointAddress(
"net.tcp://localhost/CS.WebService.Zzzzzz.Common/ZzzzzzCommonService.svc");
var binding = new NetTcpBinding { TransferMode = TransferMode.Buffered, SendTimeout = TimeSpan.MaxValue, ReceiveTimeout = TimeSpan.MaxValue, MaxReceivedMessageSize = 100000000, MaxBufferSize = 100000000 };
using (var channel = new ChannelFactory<IZzzzzzCommonService>(binding, endPoint))
{
try
{
channel.Endpoint.Contract.SessionMode = SessionMode.Allowed;
var proxy = channel.CreateChannel();
var request = new GetZipCodesRequest();
request = new GetZipCodesRequest { ZipCode = "32701" };
response = proxy.GetZipCodes(request);
}
}
}
I have debugged the code and I am getting into the entity and the dataSet is populated with the appropriate rows but when it sends the dataset back is when I get the errors.
Not sure what I am missing. I believe I have the serviceContract and dataContract members decorated correctly so not sure why it is having problems serializing the List.
The problem was the ZipCode class. It was an Entity class and it was not able to be serialized. So I deconstructed the class and it was able to send it back to the client.
I have a WCF service. In that service I have defined class marked MessageContract attribute:
[MessageContract]
public class RemoteFileInfo : IDisposable
{
[MessageHeader(MustUnderstand = true)]
public string FileName;
[MessageHeader(MustUnderstand = true)]
public long Length;
[MessageHeader(MustUnderstand = true)]
public Picture Picture;
[MessageBodyMember(Order = 1)]
public System.IO.Stream FileByteStream;
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
I have problem with fields marked MessageHeader attribute.
In WPF app (client) all fields are visible but when I use this service in Windows Phone app, fields marked MessageHeader are not visible. Only body fields are available. Is any possibility that header fields also be available?
WEll, seems that WP not support MessageContract directly. So, you can see the solution in another thread on this forum :)
I have a service exposing 2 endpoint and I would like to apply message formatting to only one of the endpoints.
To do that I am looking to capture the endpoint name in order to apply the MessageFormatter only for this specific endpoint.
This is the code of my Operation behavior attribute:
public class JsonRpcMessageValidation : Attribute, IOperationBehavior
{
#region Properties
public Type serializeType { get; set; }
public Type deserializeType { get; set; }
#endregion
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="serializeType">Serialize Type</param>
/// <param name="deserializeType">Deserialize Type</param>
public JsonRpcMessageValidation(Type serializeType, Type deserializeType)
{
this.serializeType = serializeType;
this.deserializeType = deserializeType;
}
#endregion
#region Methods
public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
JsonRpcRequestMessageInspector jrrmInspector = new JsonRpcRequestMessageInspector();
dispatchOperation.ParameterInspectors.Add(jrrmInspector);
JsonRpcMessageFormatter jrmFormatter = new JsonRpcMessageFormatter(serializeType, deserializeType);
dispatchOperation.Formatter = jrmFormatter;
}
public void Validate(OperationDescription operationDescription)
{
}
#endregion
}
I decorate the method in the interface with this attributes and I need the Type information in order to perform serialization and deserialization on the incoming and outcoming messages.
Does any know how to get the current endpoint information at this point in the code?
Thanks
I was able to work around that:
I simply used the method below to retrieve the endpoint from the dispatchOperation:
private static string GetCurrentEndpointName(System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
string endpoint = String.Empty;
if (dispatchOperation.Parent.EndpointDispatcher.EndpointAddress.Uri.Segments.Count() > 0)
{
endpoint = dispatchOperation.Parent.EndpointDispatcher.EndpointAddress.Uri.Segments[dispatchOperation.Parent.EndpointDispatcher.EndpointAddress.Uri.Segments.Count() - 1];
}
return endpoint;
}
And now it applies the Message Formatters EXCLUSIVELY to the endpoint "json" in the ApplyDispatchBehavior method:
public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
{
JsonRpcRequestMessageInspector jrrmInspector = new JsonRpcRequestMessageInspector();
dispatchOperation.ParameterInspectors.Add(jrrmInspector);
var endpoint = GetCurrentEndpointName(dispatchOperation);
//it only applies the Message Formatter to the 'json' endpoint
if (endpoint == "json")
{
JsonRpcMessageFormatter jrmFormatter = new JsonRpcMessageFormatter(serializeType, deserializeType);
dispatchOperation.Formatter = jrmFormatter;
}
}
I think it would be more suitable to use an IEndpointBehavior implementation, that you use on the appropriate endpoint where you want the custom MessageFormatter.
--larsw
Actually I need to use IOperationBehavior because I use the attribute to decorate the methods and each method have different request and response types that I use to perform serialization and deserialization on the incoming and outcoming messages otherwise yes, it would be suitable to use IEndpointBehavior.
Thx
I have a WCF service with a client application. I have complete control over both the client and server implementation. I have hundreds of methods in the WCF contract which need a piece of information supplied by the client. Instead of modifying hundreds of methods, is there a way I can send specific data from the client with every call to the service, possibly somewhere in the channel?
Maybe when the client is setting up the proxy before making the call, it can store this data somewhere in an internal property of the proxy... the data would then get sent to the server and from within the service method I could inspect the OperationContext or some other piece of memory to get this data back and use it?
Any ideas?
It sounds like you are wanting something like headers like with SOAP webservices. I'm not a WCF expert, but this looks like the WCF equivalent.
It shouldn't actually be that hard. The best way I can think of is to write an IClientMessageInspector that adds a SOAP header into the Message.Headers in its BeforeSendRequest method.
See e.g. http://weblogs.asp.net/paolopia/archive/2007/08/23/writing-a-wcf-message-inspector.aspx
You can't do this trivially. It will take some work.
It's true that SOAP Headers are the perfect way to pass out-of-band data to and/or from a service. But you already have your contract defined, and adding headers will change the contract.
I believe you'll have to start using message contracts.
Original:
[DataContract]
public class ComplexObject
{
[DataMember(Name = "Id")]
public int Id;
[DataMember]
public string Name;
}
[ServiceContract()]
public interface IMyContract
{
void MyOperation(ComplexObject co);
}
public class MyService : IMyContract
{
#region Implementation of IMyContract
public void MyOperation(ComplexObject co)
{
// use co.*
}
#endregion
}
Using Message Contracts:
[DataContract]
public class ComplexObject
{
[DataMember(Name = "Id")]
public int Id;
[DataMember]
public string Name;
}
[DataContract]
public class MyHeader
{
[DataMember]
public string UserName;
[DataMember]
public string Password;
}
[DataContract]
public class OutputHeader
{
[DataMember]
public string Token;
}
[MessageContract]
public class MyOperationRequest
{
[MessageHeader]
public MyHeader Authentication;
[MessageBodyMember]
public ComplexObject TheObject;
}
[MessageContract]
public class MyOperationResponse
{
[MessageHeader]
public OutputHeader OutputHeader;
}
[ServiceContract()]
public interface IMyContract
{
MyOperationResponse MyOperation(MyOperationRequest request);
}
public class MyService : IMyContract
{
public MyOperationResponse MyOperation(MyOperationRequest request)
{
// use request.TheObject.*
// Can also read request.Authentication.*
return new MyOperationResponse
{ OutputHeader = new OutputHeader { Token = "someToken" } };
}
}