I'm trying to use WCF to consume a 3rd-party REST service which responds with URL-encoded data:
a=1&b=2&c=3
I have this now:
[DataContract]
class Response {
[DataMember(Name="a")]
public int A { get;set;}
[DataMember(Name="b")]
public int B { get;set;}
[DataMember(Name="c")]
public int C { get;set;}
}
[ServiceContract]
interface IService
{
[OperationContract]
Response Foo();
}
But it comes back with:
There was an error checking start element of object of type Response. The data at the root level is invalid. Line 1, position 1.
WCF does not "understand" forms-data content type (application/x-www-forms-urlencoded), so it won't be able to read that response directly. You can either implement a message formatter which will be able to convert that format into your contract, or you can receive the response as a Stream (which will give you the full bytes of the response), which you can decode into your class.
The code below shows how you could implement a formatter for this operation. It's not generic, but you should get the picture of what needs to be done.
public class StackOverflow_16493746
{
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "*")]
public Stream GetData()
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-www-form-urlencoded";
return new MemoryStream(Encoding.UTF8.GetBytes("a=1&b=2&c=3"));
}
}
[ServiceContract]
interface IService
{
[WebGet]
Response Foo();
}
[DataContract]
class Response
{
[DataMember(Name = "a")]
public int A { get; set; }
[DataMember(Name = "b")]
public int B { get; set; }
[DataMember(Name = "c")]
public int C { get; set; }
}
public class MyResponseFormatter : IClientMessageFormatter
{
private IClientMessageFormatter originalFormatter;
public MyResponseFormatter(IClientMessageFormatter originalFormatter)
{
this.originalFormatter = originalFormatter;
}
public object DeserializeReply(Message message, object[] parameters)
{
HttpResponseMessageProperty httpResp = (HttpResponseMessageProperty)
message.Properties[HttpResponseMessageProperty.Name];
if (httpResp.Headers[HttpResponseHeader.ContentType] == "application/x-www-form-urlencoded")
{
if (parameters.Length > 0)
{
throw new InvalidOperationException("out/ref parameters not supported in this formatter");
}
byte[] bodyBytes = message.GetReaderAtBodyContents().ReadElementContentAsBase64();
NameValueCollection pairs = HttpUtility.ParseQueryString(Encoding.UTF8.GetString(bodyBytes));
Response result = new Response();
foreach (var key in pairs.AllKeys)
{
string value = pairs[key];
switch (key)
{
case "a":
result.A = int.Parse(value);
break;
case "b":
result.B = int.Parse(value);
break;
case "c":
result.C = int.Parse(value);
break;
}
}
return result;
}
else
{
return this.originalFormatter.DeserializeReply(message, parameters);
}
}
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
throw new NotSupportedException("This is a reply-only formatter");
}
}
public class MyClientBehavior : WebHttpBehavior
{
protected override IClientMessageFormatter GetReplyClientFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint)
{
return new MyResponseFormatter(base.GetReplyClientFormatter(operationDescription, endpoint));
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<IService> factory = new ChannelFactory<IService>(new WebHttpBinding(), new EndpointAddress(baseAddress));
factory.Endpoint.Behaviors.Add(new MyClientBehavior());
IService proxy = factory.CreateChannel();
Response resp = proxy.Foo();
Console.WriteLine("a={0},b={1},c={2}", resp.A, resp.B, resp.C);
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
Related
I have a self hosted WCF service for handling HTTP POST request.
My WCF service method will handle 2 types of request (1. getting data, 2. Do some action with given data).
My scenario :
1. Started Action request with large amount of data. : during the starting of that action do some processing.
2. client reads some results.
3. sending the remaining data for the previous action.
I implemented this using 'TcpListener' it is working.
Problem:
when i try to implement this scenario using WCF, i have got the 'Bad request' during the first action request.
[ServiceContract]
public interface ITest
{
[OperationContract, WebInvoke(Method = "POST", UriTemplate = "{*pathname}")]
Stream GetResponse(string pathname, Stream requestBody);
}
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Exact, ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext = false, IncludeExceptionDetailInFaults = true)]
class TestService : ITest
{
public Uri BaseUri { get; private set; }
public IPAddress Address { get; private set; }
public Int32 Port { get; private set; }
public bool IsStarted { get { return Host != null; } }
public ServiceHost Host { get; private set; }
public TestService()
{
}
public TestService(IPAddress ipAddress, int port)
{
if (ipAddress == null) { throw new ArgumentNullException("Address"); }
this.Address = ipAddress;
this.Port = port;
this.BaseUri = new Uri(string.Format("http://{0}:{1}", this.Address, this.Port));
}
public void Start()
{
if (IsStarted) { throw new InvalidOperationException("Service is already started."); }
Host = CreateServiceHost();
Host.Open();
}
public void Stop()
{
if (!IsStarted) { throw new InvalidOperationException("Service is already stopped."); }
Host.Close();
Host = null;
}
private ServiceHost CreateServiceHost()
{
ServiceHost host = new ServiceHost(typeof(TestService), this.BaseUri);
WebHttpBinding webhttpBinding = new WebHttpBinding();
webhttpBinding.MaxBufferPoolSize = int.MaxValue;
webhttpBinding.MaxBufferSize = int.MaxValue;
webhttpBinding.MaxReceivedMessageSize = int.MaxValue;
CustomBinding binding = new CustomBinding(webhttpBinding);
WebMessageEncodingBindingElement webEncoding = binding.Elements.Find<WebMessageEncodingBindingElement>();
webEncoding.ContentTypeMapper = new RawMapper();
host.AddServiceEndpoint(typeof(ITest), binding, new Uri(this.BaseUri.AbsoluteUri)).Behaviors.Add(new WebHttpBehavior());
return host;
}
public Stream GetResponse(string pathname, Stream requestBody)
{
Stream response=null;
/************** Process 'requestBody' **************/
//requestBody contains "MY_ACTION"
//{
// Find the start delimeter from response : START processing
// Find the end delimeter from response : STOP processing
//}
//requestBody contains "GET_MY_DATA"
//{
// Find data and send response
//}
return response;
}
}
public class RawMapper : WebContentTypeMapper
{
public override WebContentFormat GetMessageFormatForContentType(string contentType)
{
return WebContentFormat.Raw;
}
}
Any help/guidance would be great as I'm really stuck on this.
I'm writing a simple client for a web service using WCF. Unfortunately, the web service only answers with JSONP messages, not plain JSON.
Is that possible to use built-in features from .NET 4.0 to do this or do I need to extend something else to strip function name, { and } from the answer I get from the server? I know how to read JSON responses, but not JSONP yet.
What you need is a custom message encoder. On the server side, it's the encoder which adds the padding (function call) to the response, so you need something similar on the client side to remove that padding before handling the message (likely delegating it to another encoder). The other thing you'll need to worry about at the encoder is that often the content-type used for JSONP (application/x-javascript) is not recognized as a JSON content-type (because it's not, it's a function call), so the encoder should also "translate" that content-type into one which is understood by the encoder to which the call is delegated.
The code below shows an example of such an encoder. The service has been modified to always wrap the result, as you mentioned your service does.
public class StackOverflow_11255528
{
[ServiceContract]
public interface ICalculator
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
int Add(int x, int y);
[WebGet(ResponseFormat = WebMessageFormat.Json)]
int Subtract(int x, int y);
}
[ServiceContract]
public class CalculatorService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream Add(int x, int y)
{
return ReturnWrapped(x + y);
}
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Stream Subtract(int x, int y)
{
return ReturnWrapped(x - y);
}
private Stream ReturnWrapped(int result)
{
string callback = "Something";
string response = string.Format("{0}({1});", callback, result);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-javascript";
return new MemoryStream(Encoding.UTF8.GetBytes(response));
}
}
public class JsonpAwareClientMessageEncodingBindingElement : MessageEncodingBindingElement
{
WebMessageEncodingBindingElement webEncoding;
public JsonpAwareClientMessageEncodingBindingElement()
{
this.webEncoding = new WebMessageEncodingBindingElement();
}
public override MessageEncoderFactory CreateMessageEncoderFactory()
{
return new JsonpAwareClientMessageEncoderFactory(this.webEncoding.CreateMessageEncoderFactory());
}
public override MessageVersion MessageVersion
{
get { return this.webEncoding.MessageVersion; }
set { this.webEncoding.MessageVersion = value; }
}
public override BindingElement Clone()
{
return new JsonpAwareClientMessageEncodingBindingElement();
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
context.BindingParameters.Add(this);
return context.BuildInnerChannelFactory<TChannel>();
}
class JsonpAwareClientMessageEncoderFactory : MessageEncoderFactory
{
private MessageEncoderFactory factory;
public JsonpAwareClientMessageEncoderFactory(MessageEncoderFactory factory)
{
this.factory = factory;
}
public override MessageEncoder Encoder
{
get { return new JsonpAwareClientMessageEncoder(this.factory.Encoder); }
}
public override MessageVersion MessageVersion
{
get { return this.factory.MessageVersion; }
}
}
class JsonpAwareClientMessageEncoder : MessageEncoder
{
private MessageEncoder encoder;
public JsonpAwareClientMessageEncoder(MessageEncoder encoder)
{
this.encoder = encoder;
}
public override string ContentType
{
get { return this.encoder.ContentType; }
}
public override string MediaType
{
get { return this.encoder.MediaType; }
}
public override MessageVersion MessageVersion
{
get { return this.encoder.MessageVersion; }
}
public override bool IsContentTypeSupported(string contentType)
{
if (contentType == "application/x-javascript")
{
contentType = "application/json";
}
return this.encoder.IsContentTypeSupported(contentType);
}
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
if (contentType == "application/x-javascript")
{
contentType = "application/json";
}
byte openParenthesis = (byte)'(';
byte closeParenthesis = (byte)')';
int startOfParenthesis = buffer.Offset;
int count = buffer.Count;
while (buffer.Array[startOfParenthesis] != openParenthesis)
{
startOfParenthesis++;
count--;
}
// Skipped 'Func', now skipping '('
startOfParenthesis++;
count--;
// Now need to trim the closing parenthesis and semicolon, if any
int endOfParenthesis = buffer.Offset + buffer.Count - 1;
while (buffer.Array[endOfParenthesis] != closeParenthesis)
{
endOfParenthesis--;
count--;
}
// Skipped back to ')', now remove it
endOfParenthesis--;
count--;
return this.encoder.ReadMessage(new ArraySegment<byte>(buffer.Array, startOfParenthesis, count), bufferManager, contentType);
}
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
{
throw new NotSupportedException("Streamed mode not supported");
}
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
return this.encoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);
}
public override void WriteMessage(Message message, Stream stream)
{
throw new NotSupportedException("Streamed mode not supported");
}
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(CalculatorService), new Uri(baseAddress));
WebHttpBinding binding = new WebHttpBinding { CrossDomainScriptAccessEnabled = true };
host.AddServiceEndpoint(typeof(CalculatorService), binding, "").Behaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress + "/Add?x=5&y=8&callback=Func"));
CustomBinding clientBinding = new CustomBinding(
new JsonpAwareClientMessageEncodingBindingElement(),
new HttpTransportBindingElement { ManualAddressing = true });
ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(clientBinding, new EndpointAddress(baseAddress));
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
ICalculator proxy = factory.CreateChannel();
Console.WriteLine(proxy.Subtract(456, 432));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
There is no direct way which I know but lets first try to understand difference between a JSON and JSONP
//JSON
{"prop":"val"}
//JSONP
func({"prop":"val"});
To get the JSON string you could simply strip every thing in between the "(" and ")" braces and then use different JSON libraries to convert it in to objects.
string jsonString = Regex.Match(jsonpString, #"\(([^)]*)\)").Groups[1].Value
I have a resource available at
http://localhost/resource
I do not have any route like
http:/localhost/resource?name=john
but when I try to hit the above URI I get the result of http://localhost/resource. I was expecting a 404.
Any idea why its ignoring ?name=john and match the url ??
Query string parameters are optional and not "officially" part of the address - it goes from the scheme to the path (via host and port). There are many scenarios where you have one operation at address http://something.com/path, and in the operation code you look at the query string parameters to make some decision. For example, the code below looks for a "format" parameter in the query string which may or may not be passed, and all requests (with or without it) are correctly routed to the operation.
public class StackOverflow_10422764
{
[DataContract(Name = "Person", Namespace = "")]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "/NoQueryParams")]
public Person GetPerson()
{
string format = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
if (format == "xml")
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
}
else if (format == "json")
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
}
return new Person { Name = "Scooby Doo", Age = 10 };
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
host.Open();
Console.WriteLine("Host opened");
WebClient c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress + "/NoQueryParams"));
c = new WebClient();
Console.WriteLine(c.DownloadString(baseAddress + "/NoQueryParams?format=json"));
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
Update after comments:
If you want to force the request to contain exactly the parameters specified in the template, then you can use something like a message inspector to validate that.
public class StackOverflow_10422764
{
[DataContract(Name = "Person", Namespace = "")]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
[ServiceContract]
public class Service
{
[WebGet(UriTemplate = "/NoQueryParams")]
public Person GetPerson()
{
string format = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["format"];
if (format == "xml")
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
}
else if (format == "json")
{
WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
}
return new Person { Name = "Scooby Doo", Age = 10 };
}
[WebGet(UriTemplate = "/TwoQueryParam?x={x}&y={y}")]
public int Add(int x, int y)
{
return x + y;
}
}
public class MyForceQueryMatchBehavior : IEndpointBehavior, IDispatchMessageInspector
{
#region IEndpointBehavior Members
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
}
public void Validate(ServiceEndpoint endpoint)
{
}
#endregion
#region IDispatchMessageInspector Members
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
UriTemplateMatch uriTemplateMatch = (UriTemplateMatch)request.Properties["UriTemplateMatchResults"];
// TODO: may need to deal with the case of implicit UriTemplates, or if you want to allow for some query parameters to be ommitted
List<string> uriTemplateQueryVariables = uriTemplateMatch.Template.QueryValueVariableNames.Select(x => x.ToLowerInvariant()).ToList();
List<string> requestQueryVariables = uriTemplateMatch.QueryParameters.Keys.OfType<string>().Select(x => x.ToLowerInvariant()).ToList();
if (uriTemplateQueryVariables.Count != requestQueryVariables.Count || uriTemplateQueryVariables.Except(requestQueryVariables).Count() > 0)
{
throw new WebFaultException(HttpStatusCode.NotFound);
}
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
}
#endregion
}
static void SendRequest(string uri)
{
Console.WriteLine("Request to {0}", uri);
WebClient c = new WebClient();
try
{
Console.WriteLine(" {0}", c.DownloadString(uri));
}
catch (WebException e)
{
HttpWebResponse resp = e.Response as HttpWebResponse;
Console.WriteLine(" ERROR => {0}", resp.StatusCode);
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(Service), new WebHttpBinding(), "");
endpoint.Behaviors.Add(new WebHttpBehavior());
endpoint.Behaviors.Add(new MyForceQueryMatchBehavior());
host.Open();
Console.WriteLine("Host opened");
SendRequest(baseAddress + "/NoQueryParams");
SendRequest(baseAddress + "/NoQueryParams?format=json");
SendRequest(baseAddress + "/TwoQueryParam?x=7&y=9&z=other");
SendRequest(baseAddress + "/TwoQueryParam?x=7&y=9");
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
I have a WCF Service, And I inspect that using MessageInspector ( inherit IDispatchMessageInspector)
I want to do some thing before running service and result of that ı want not run service.
I want to prevent client call but client dont receive exception.
Can you help me
This scenario looks like the post in the MSDN WCF forum entitled "IDispatchMessageInspector.AfterReceiveRequest - skip operation and manually generate custom response instead". If this is what you need (when you receive a message in the inspector, you decide that you want to skip the service operation, but return a message to the client and the client should not see an exception), then this answer should work for you as well. Notice that you'll need to create the response message in the same format as the client expects, otherwise you'll have an exception.
This code uses three of the (many) WCF extensibility points to achieve that scenario, a message inspector (as you've mentioned you're using), a message formatter and an operation invoker. I've blogged about them in an ongoing series about WCF extensibility at http://blogs.msdn.com/b/carlosfigueira/archive/2011/03/14/wcf-extensibility.aspx.
public class Post_55ef7692_25dc_4ece_9dde_9981c417c94a
{
[ServiceContract(Name = "ITest", Namespace = "http://tempuri.org/")]
public interface ITest
{
[OperationContract]
string Echo(string text);
}
public class Service : ITest
{
public string Echo(string text)
{
return text;
}
}
static Binding GetBinding()
{
BasicHttpBinding result = new BasicHttpBinding();
return result;
}
public class MyOperationBypasser : IEndpointBehavior, IOperationBehavior
{
internal const string SkipServerMessageProperty = "SkipServer";
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyInspector(endpoint));
}
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
}
public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
dispatchOperation.Formatter = new MyFormatter(dispatchOperation.Formatter);
dispatchOperation.Invoker = new MyInvoker(dispatchOperation.Invoker);
}
public void Validate(OperationDescription operationDescription)
{
}
class MyInspector : IDispatchMessageInspector
{
ServiceEndpoint endpoint;
public MyInspector(ServiceEndpoint endpoint)
{
this.endpoint = endpoint;
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
Message result = null;
HttpRequestMessageProperty reqProp = null;
if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
reqProp = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
}
if (reqProp != null)
{
string bypassServer = reqProp.Headers["X-BypassServer"];
if (!string.IsNullOrEmpty(bypassServer))
{
result = Message.CreateMessage(request.Version, this.FindReplyAction(request.Headers.Action), new OverrideBodyWriter(bypassServer));
}
}
return result;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
Message newResult = correlationState as Message;
if (newResult != null)
{
reply = newResult;
}
}
private string FindReplyAction(string requestAction)
{
foreach (var operation in this.endpoint.Contract.Operations)
{
if (operation.Messages[0].Action == requestAction)
{
return operation.Messages[1].Action;
}
}
return null;
}
class OverrideBodyWriter : BodyWriter
{
string bypassServerHeader;
public OverrideBodyWriter(string bypassServerHeader)
: base(true)
{
this.bypassServerHeader = bypassServerHeader;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("EchoResponse", "http://tempuri.org/");
writer.WriteStartElement("EchoResult");
writer.WriteString(this.bypassServerHeader);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
class MyFormatter : IDispatchMessageFormatter
{
IDispatchMessageFormatter originalFormatter;
public MyFormatter(IDispatchMessageFormatter originalFormatter)
{
this.originalFormatter = originalFormatter;
}
public void DeserializeRequest(Message message, object[] parameters)
{
if (message.Properties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty))
{
Message returnMessage = message.Properties[MyOperationBypasser.SkipServerMessageProperty] as Message;
OperationContext.Current.IncomingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage);
OperationContext.Current.OutgoingMessageProperties.Add(MyOperationBypasser.SkipServerMessageProperty, returnMessage);
}
else
{
this.originalFormatter.DeserializeRequest(message, parameters);
}
}
public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
{
if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty))
{
return null;
}
else
{
return this.originalFormatter.SerializeReply(messageVersion, parameters, result);
}
}
}
class MyInvoker : IOperationInvoker
{
IOperationInvoker originalInvoker;
public MyInvoker(IOperationInvoker originalInvoker)
{
if (!originalInvoker.IsSynchronous)
{
throw new NotSupportedException("This implementation only supports synchronous invokers");
}
this.originalInvoker = originalInvoker;
}
public object[] AllocateInputs()
{
return this.originalInvoker.AllocateInputs();
}
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
if (OperationContext.Current.IncomingMessageProperties.ContainsKey(MyOperationBypasser.SkipServerMessageProperty))
{
outputs = null;
return null; // message is stored in the context
}
else
{
return this.originalInvoker.Invoke(instance, inputs, out outputs);
}
}
public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
throw new NotSupportedException();
}
public bool IsSynchronous
{
get { return true; }
}
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), GetBinding(), "");
endpoint.Behaviors.Add(new MyOperationBypasser());
foreach (var operation in endpoint.Contract.Operations)
{
operation.Behaviors.Add(new MyOperationBypasser());
}
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>(GetBinding(), new EndpointAddress(baseAddress));
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.Echo("Hello"));
Console.WriteLine("And now with the bypass header");
using (new OperationContextScope((IContextChannel)proxy))
{
HttpRequestMessageProperty httpRequestProp = new HttpRequestMessageProperty();
httpRequestProp.Headers.Add("X-BypassServer", "This message will not reach the service operation");
OperationContext.Current.OutgoingMessageProperties.Add(
HttpRequestMessageProperty.Name,
httpRequestProp);
Console.WriteLine(proxy.Echo("Hello"));
}
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
How can I obtain the domain name or full URL of the requester?
I'm not sure that I understand your question, but if you need the domain name of the Windows user making the call to a service operation, use this:
OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name
This will return "{domain}\{username}".
Try this and let me know what you think (you'll probably want to paste this code into an mstest project):
[TestClass]
public class AlternativeCredentials
{
// Contracts
[ServiceContract]
interface IMyContract
{
[OperationContract]
string GetUserName();
}
// Service
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
class MyService : IMyContract
{
public string GetUserName()
{
return OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name;
}
}
// Client
class MyContractClient : ClientBase<IMyContract>, IMyContract
{
public MyContractClient() { }
public MyContractClient(Binding binding, string address) :
base(binding, new EndpointAddress(address)) { }
public string GetUserName()
{ return Channel.GetUserName(); }
}
#region Host
static string address = "net.tcp://localhost:8001/" + Guid.NewGuid().ToString();
static ServiceHost host;
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
host = new ServiceHost(typeof(MyService));
host.AddServiceEndpoint(typeof(IMyContract), new NetTcpBinding(), address);
host.Open();
}
[ClassCleanup()]
public static void MyClassCleanup()
{
if (host.State == CommunicationState.Opened)
host.Close();
}
#endregion
[TestMethod]
public void UseUserNameCredentials()
{
using (MyContractClient proxy =
new MyContractClient(new NetTcpBinding(), address))
{
proxy.ClientCredentials.UserName.UserName = "MyUsername";
proxy.ClientCredentials.UserName.Password = "MyPassword";
proxy.Open();
Assert.AreEqual("EMS\\magood", proxy.GetUserName());
proxy.Close();
}
}
}