InstanceContextMode = InstanceContextMode.PerSession is not working - c#

I'm new to WCF and I wrote a sample WCF service which uses the InstanceContextMode. When I'm using the PerSession, my counter value doesn't gets incremented. Why doesn't it uses the same instance for every service call.
Below is my code
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service1 : IService1
{
int count;
public int Add(int a, int b)
{
count++;
return a + b;
}
public int GetCount()
{
return count;
}
}
WebConfig
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
Client.cs
DemoWCFService.Service1Client client = new DemoWCFService.Service1Client();
Console.WriteLine(""+ client.Add(10,20));
Console.WriteLine("" + client.Add(10, 20));
Console.WriteLine("" + client.Add(10, 20));
Console.WriteLine("" + client.GetCount());
Console.ReadKey();
Please help me with this.

BasicHttpBinding doesn't support PerSession.
You had better use binding that supports session such as WSHttpBinding, WS2007HttpBinding.
To ensure you are using binding that supports session, you could use a service behavior
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
If your binding doesn't support session, it will cause error.

Related

How to limit wcf service method for a specific ip

Here is my wcf service method:
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/CheckID/{id}")]
public string CheckID(string id)
{
/*Check reuqest where it comes from */
}
I want my method send response OK if it comes/is invoked from http://particularIP.com, unless response Bad request.
How can i do that?
You can use IP Filter in web.config file, like :-
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="RestrictedServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<IPFilter filter="172.*.*.* 127.0.0.1" />
</behavior>
</serviceBehaviors>
Edited
Or use can ServiceAuthorizationManager.CheckAccessCore in which you get client IP from OperationContext.
https://msdn.microsoft.com/en-us/library/system.servicemodel.serviceauthorizationmanager.checkaccesscore.aspx
Edit 2
using System.ServiceModel;
using System.ServiceModel.Channels;
OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;

WCF Service not receiving data in POST

I have a WCF Service with a SOAP endpoint. I added a REST endpoint and the Get methods are working just fine. I am having trouble with a POST method which takes in an object and returns a different object. When I pass in my object, I get this error back:
"Message":"Object reference not set to an instance of an object."
Here's the code to call the service:
string URL = "http://qa.acct.webservice";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var request = new RequestGetInventory
{
BrandIDs = new string[] { "4", "42" },
AccountID = "9900003"
};
var resp = client.PostAsJsonAsync("/AxaptaService.svc/rest/GetInventory", request);
response = resp.Result;
if (response.IsSuccessStatusCode)
{
var temp = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(temp); //error message received here.
}
The RequestGetInventory object is defined as follows:
[DataContract]
public class RequestGetInventory
{
[DataMember]
public string[] BrandIDs { get; set; }
[DataMember]
public string AccountID { get; set; }
}
The contract for the webservice is defined as follows:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
ResponseGetInventory GetInventory(RequestGetInventory Request);
I tried playing around with the WebInvoke parameters, but received the same error message for all viable attempts.
And this is how my web.config is set up:
<system.serviceModel>
<services>
<service behaviorConfiguration="" name="Proj.AxaptaUS.WebService.AxaptaService">
<endpoint address="rest" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="Proj.Interfaces.Axapta3.IAxaptaService"></endpoint>
<endpoint address="" binding="basicHttpBinding" contract="Proj.Interfaces.Axapta3.IAxaptaService"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true" />
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
I am not entirely sure what I'm doing wrong because I can access this using SOAP just fine. It seems like it is not getting any values for the object which I passed in, thus causing the object reference error.
Any help would be greatly appreciated! Thanks!
#jstreet posted a comment which ended up working.
I changed BodyStyle = WebMessageBodyStyle.WrappedRequest to BodyStyle = WebMessageBodyStyle.Bare and removed <enableWebScript/> from config file.
After doing those things, it started to work correctly! thanks #jstreet!

Why Thread.CurrentPrincipal.Identity.IsAuthenticated is always false?

I have this WCF service and I'm trying to apply authentication and authorization mechanism in it.
It's my first time to do this, what I have is this web.config serviceModel tag for the service:
<system.serviceModel>
<services>
<service name="RoleBasedServices.SecureServiceExternal" behaviorConfiguration="externalServiceBehavior">
<endpoint contract="AuthService.IService1" binding="wsHttpBinding" bindingConfiguration="wsHttpUsername" />
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="wsHttpUsername">
<security mode="Message">
<message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!--To avoid disclosing metadata information, set the values below to false before deployment-->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!--To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information-->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
<behavior name="externalServiceBehavior">
<serviceAuthorization principalPermissionMode="UseAspNetRoles" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider" />
<serviceCertificate findValue="RPKey" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
What I want to do is very simple, I don't know if I need all this tags I'm just trying.
What I want to do is from the client side to add reference for the service and first call the MyLogin:
AuthService.Service1Client s = new AuthService.Service1Client();
s.Login();
Then call the other restricted method and let it be GetData:
s.GetData()
At service side in Login method, and only for test purposes, I'm doing this:
public void Login()
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("Bob"), new[] { "Admin" });
FormsAuthentication.SetAuthCookie("BobUserName", false);
}
An the restricted method will be:
[PrincipalPermission(SecurityAction.Demand, Role = "Admin")]
public void GetData()
{
return "Hello";
}
That all I have in service and client, what I'm missing?
Every time ,in debug, I check Thread.CurrentPrincipal in Login method I found Thread.CurrentPrincipal.Identity.IsAuthenticated equals true but even though when the client calls the GetData() method it's Access Denied.
PS: I'm using console application to do my tests does it make any difference ?
Thanks
Here is a very nice article that could possibly lead to a solution.
The general idea is that you have 2 object for the Principal.
HttpContext.Current.User and Thread.CurrentPrincipal. You are setting the Thread.CurrentPrincipal at the time HttpContext.Current.User is already instantiated and the role of it is left to default. You may want to try something like:
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("Bob"), new[] { "Admin" });
The reason calls to GetData() are denied is because WCF doesn't know anything about the Forms Authentication cookie that was set during Login().
It doesn't make a difference that you're a using console app. You could try the following approach.
Set the cookie in Login():
var cookie = FormsAuthentication.GetAuthCookie(username, true);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), null);
FormsAuthentication.SetAuthCookie(HttpContext.Current.User.Identity.Name, true);
Then in your console app:
public static void TestLoginAndGetData()
{
var sharedCookie = string.Empty;
using (var client = new YourClient())
using (new OperationContextScope(client.InnerChannel))
{
client.Login("username", "password");
// get the cookie from the response
HttpResponseMessageProperty response = (HttpResponseMessageProperty)
OperationContext.Current.IncomingMessageProperties[
HttpResponseMessageProperty.Name];
sharedCookie = response.Headers["Set-Cookie"];
// add it to the request
HttpRequestMessageProperty request = new HttpRequestMessageProperty();
request.Headers["Cookie"] = sharedCookie;
OperationContext.Current.OutgoingMessageProperties[
HttpRequestMessageProperty.Name] = request;
var result = client.GetData();
Console.WriteLine(result);
}
}
You might also consider changing the return type of GetData() to string.

WCF - ValidateUserNamePasswordCore() method in custom UserNameSecurityTokenAuthenticator not called

I have defined an own ServiceCredentials provider:
class PasswordServiceCredentials : ServiceCredentials
{
}
That provider generates a custom SecurityTokenManager in CreateSecurityTokenManager() method when I start my ServiceHost:
public override SecurityTokenManager CreateSecurityTokenManager()
{
if (this.UserNameAuthentication.UserNamePasswordValidationMode == UserNamePasswordValidationMode.Custom)
{
return new PasswordSecurityTokenManager(this);
}
return base.CreateSecurityTokenManager();
}
The PasswordSecurityTokenManager class:
class PasswordSecurityTokenManager : ServiceCredentialsSecurityTokenManager
{
}
The instance generates a custom SecurityTokenAuthenticator in CreateSecurityTokenAuthenticator() method:
public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver)
{
outOfBandTokenResolver = null;
return new PasswordSecurityTokenAuthenticator(this.ServiceCredentials
.UserNameAuthentication
.CustomUserNamePasswordValidator);
}
The generated instance is a custom CustomUserNameSecurityTokenAuthenticator.
The problem is that the overwritten ValidateUserNamePasswordCore() method is NOT CALLED at any time:
protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateUserNamePasswordCore(String userName, String password)
{
ReadOnlyCollection<IAuthorizationPolicy> currentPolicies = base.ValidateUserNamePasswordCore(userName, password);
List<IAuthorizationPolicy> newPolicies = new List<IAuthorizationPolicy>();
if (currentPolicies != null)
{
newPolicies.AddRange(currentPolicies.OfType<IAuthorizationPolicy>());
}
newPolicies.Add(new PasswordAuthorizationPolicy(userName, password));
return newPolicies.AsReadOnly();
}
In my custom IAuthorizationPolicy provider PasswordAuthorizationPolicy I want to set a custom pricipal for the EvaluationContext in Evaluate() method.
But if the upper method is not called, no additional IAuthorizationPolicy item can be defined.
What wrong or missing here?
I DO NOT use XML to configure my service, I do this 100% in C# code!
EDIT: The code ist based on the following blog article: http://www.neovolve.com/post/2008/04/07/wcf-security-getting-the-password-of-the-user.aspx
OK, I'm only asking because you never mentioned anything about your config file in your post, but are you setting your serviceCredentials type in your serviceBehaviors? Example:
<behaviors>
<serviceBehaviors>
<behavior name="YourCustomBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials type="Your.Namespace.PasswordServiceCredentials, Your.Namespace">
<serviceCertificate findValue="localhost" x509FindType="FindBySubjectName" />
<userNameAuthentication userNamePasswordValidationMode="Custom" />
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom" />
</behavior>
</serviceBehaviors>
</behaviors>
And if you are, are you referencing "YourCustomBehavior" in your behaviorConfiguration on your service node? Example:
<services>
<service behaviorConfiguration="YourCustomBehavior"
name="Your.Service.Namespace.YourService">
<endpoint address="net.tcp://..."
binding="netTcpBinding" bindingConfiguration="netTcpBindingConfig"
contract="Your.Service.Interface.Namespace.IYourService" />
</service>
</services>
It might be as obvious as that.
(source: avivacommunityfund.org)

Binding in the client + WCF

I use visual studio 11 to add service (Add service Reference).
When I added the service Article, I have An articleClient with one constructor:
public RssArticleServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
How can I use this constructor, i don't know which value of binding should I use??
Any example or sample please??
Merci
Best regards
I do this:
BasicHttpSecurityMode securitymode = BasicHttpSecurityMode.Transport; BasicHttpBinding binding = new BasicHttpBinding(securitymode); binding.MaxReceivedMessageSize = int.MaxValue; binding.MaxBufferSize = int.MaxValue; Uri uri = new Uri("adresse/RssArticleService.svc";); _clientArticles = new RssArticleServiceClient(binding, new EndpointAddress("adresse/RssArticleService.svc";)); var result=await _clientArticles.GetRssDataAsync("1", "fr");
And A cath this error:
**here was no endpoint listening at adresse/RssArticleService.svc that could accept the message. This is often caused by an incorrect address or SOAP**
What can i do, should i change the type of binding??
This is my implementation :
BasicHttpSecurityMode securitymode = HostSource.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase) ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None;
BasicHttpBinding binding = new BasicHttpBinding(securitymode);
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
Uri uri = new Uri(Application.Current.Host.Source, "../service.svc");
_client = new RssArticleServiceClient(binding, new EndpointAddress(uri))
EDIT : you need to add this in your web.config :
<system.serviceModel>
<services>
<service name="namespace.RssArticleService"
behaviorConfiguration="RssArticleServiceBehavior">
<endpoint address=""
binding="basicHttpBinding"
contract="namespace.IRssArticleService"/>
</service>
</services>
<serviceBehaviors>
<behavior name="RssArticleServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>

Categories