wcf 400 bad requset error - asp.net

i am having this issue and i looked in all the web and saw lots of answers but nothing helped me
my issue is that i every time i make get from the wcf service its 400 bad request
but when i run the wcf test client it works fine
i am using vs 2015
my config file (which vs generated automatically )
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IProductService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/Test/Service1/"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IProductService"
contract="ServiceReference.IProductService" name="BasicHttpBinding_IProductService" />
</client>
<services>
<service name="Test.ProductService">
<endpoint address="" binding="basicHttpBinding" contract="Test.IProductService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/Test/Service1/" />
</baseAddresses>
</host>
</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>
</behaviors>
</system.serviceModel>
<connectionStrings>
<add name="modelEntities" connectionString="metadata=res://*/Products.csdl|res://*/Products.ssdl|res://*/Products.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
and the service is
public interface IProductService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,UriTemplate = "/GetProducts")]
List<Product> GetProducts();
}
and this is the impplement method
public List<Product> GetProducts()
{
modelEntities context = new modelEntities();
var productEntity = (from p in context.productEntities select p);
List<Product> products = new List<Product>();
foreach (var item in productEntity)
{
products.Add(TranslateProductEntityToProduct(item));
}
return products;
}
i was trying without the webinvoke
also tried webget
and also try to replace the basichttpbinding with webbinding
and also look for many answers here and on the net and nothing helped me
hope you an help me
Thanks

Related

WCF weHttpBinding - specifies multiple request body parameters to be serialized without any wrapper elements

i have searched the forum for a while now and tried a few different things, but i still am not able to call run the WCF from IIS5.
I set up passthrough auth.
Authentication IIS 7.5 settings
Here is the ASP.NET app weconfig:
<system.web>
<sessionState timeout="2000"></sessionState>
<compilation strict="false" explicit="true" targetFramework="4.0" />
<authentication mode="Windows" />
<authorization>
<allow users="d_torreggiani" />
<deny users="*, ?" />
<!-- explicitly deny all others, including anonymous -->
</authorization>
<!--
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
</authentication>
-->
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<customErrors mode="Off" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<!--
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
-->
<bindings>
<!--
<wsHttpBinding>
<binding name="wsHttpBinding_ISER_ProjectStructure" sendTimeout="00:25:00">
<security mode="Transport">
<transport clientCredentialType="Windows"/>
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</wsHttpBinding>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISER_ProjectStructure" sendTimeout="00:25:00">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
-->
<webHttpBinding >
<binding name="WebHttpBinding_ISER_ProjectStructure" sendTimeout="00:25:00" >
<security mode="TransportCredentialOnly" >
<transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
<!--<message clientCredentialType="UserName" algorithmSuite="Default" />-->
</security>
</binding>
</webHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8085/SER_ProjectStructure.svc" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_ISER_ProjectStructure" contract="SER_ProjectStructureRef.ISER_ProjectStructure" name="WebHttpBinding_ISER_ProjectStructure" behaviorConfiguration="webHttp"/>
</client>
</system.serviceModel>
</configuration>
and here is the WCF service web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
and here is the contract declaration
<ServiceContract()>
Public Interface ISER_ProjectStructure
<OperationContract()> _
<WebInvoke(BodyStyle:=WebMessageBodyStyle.WrappedRequest, Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _
Function RunProcedure(ByVal pPath As String, ByVal pProjectName As String) As Result
End Interface
On my development machine it works just fine, but when i publish it i keep getting this error:
Operation 'RunProcedure' of contract 'ISER_ProjectStructure' specifies
multiple request body parameters to be serialized without any wrapper
elements. At most one body parameter can be serialized without wrapper
elements. Either remove the extra body parameters or set the BodyStyle
property on the WebGetAttribute/WebInvokeAttribute to Wrapped.
with this stack:
[InvalidOperationException: Operation 'RunProcedure' of contract 'ISER_ProjectStructure' specifies multiple request body parameters to be serialized without any wrapper elements. At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped.]
System.ServiceModel.Description.WebHttpBehavior.TryGetNonMessageParameterType(MessageDescription message, OperationDescription declaringOperation, Boolean isRequest, Type& type) +972660
System.ServiceModel.Description.WebHttpBehavior.ValidateBodyStyle(OperationDescription operation, Boolean request) +209
System.ServiceModel.Description.<>c__DisplayClassa.<GetRequestClientFormatter>b__4() +83
System.ServiceModel.Description.<>c__DisplayClass7.<GetRequestClientFormatter>b__3() +244
System.ServiceModel.Description.WebHttpBehavior.GetRequestClientFormatter(OperationDescription operationDescription, ServiceEndpoint endpoint) +435
System.ServiceModel.Description.WebHttpBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) +321
System.ServiceModel.Description.DispatcherBuilder.ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime clientRuntime) +259
System.ServiceModel.Description.DispatcherBuilder.BuildProxyBehavior(ServiceEndpoint serviceEndpoint, BindingParameterCollection& parameters) +432
System.ServiceModel.Channels.ServiceChannelFactory.BuildChannelFactory(ServiceEndpoint serviceEndpoint, Boolean useActiveAutoClose) +102
System.ServiceModel.ChannelFactory.CreateFactory() +46
System.ServiceModel.ChannelFactory.OnOpening() +86
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +570
System.ServiceModel.ChannelFactory.EnsureOpened() +117
System.ServiceModel.ChannelFactory`1.CreateChannel(EndpointAddress address, Uri via) +477
System.ServiceModel.ClientBase`1.CreateChannel() +58
System.ServiceModel.ClientBase`1.CreateChannelInternal() +48
System.ServiceModel.ClientBase`1.get_Channel() +464
WebInterfaceProjectStructureRoot._Default.Button1_Click(Object sender, EventArgs e) in C:\Users\d_torreggiani\Documents\Visual Studio 2010\Projects\USProjectStructure\WebApplication1\Default.aspx.vb:18
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
What can it be, i do not understand.
Thanks in advance for any hint.
AFAIK if you are using 'wrappedrequest' you should have only a single entity containing the input properties.
So you should create a DTO class having input properties,then you should pass this instance of class in wcf method.

Fileless Restful WCF not working when hosted in local IIS7 but works run locally

I have a restful .svc-less,fileless service which returns JSon data. It works fine if it run it locally but when i host in in my local IIS7, i get error
Request Error
The server encountered an error processing the request. See server logs for more details.
This is the path of the web host application in IIS.
localhost:8080/AdventureWorksHost/EmployeeService/Employees/GetEmployees
But works fine when I run it in my visual studio
localhost:50182/employeeService/Employees/Getemployees
where AdventureWorksHost is ApplicationName hosted under Default Web Site in IIS. And EmployeeService is name of the Service which I service I added in global.asax.cs with standard endpoints in webconfig file
RouteTable.Routes.Add(new ServiceRoute("EmployeeService", new WebServiceHostFactory(), typeof(Services.EmployeeService.EmployeeService)));
I have checked several suggestion in stackoverflow and other sites for similar issue but none of solution works for me.
1)I assigned default port number 8080 for Default Web Site(under which my project is hosted) in IIS7 and made sure this port number is not blocked by firewall or any anti-virus application in my computer.
2)I check WCF HTTP and NON-HTTP activations, WCF Services for all .Net Framework avaiable in Windows Features
Windows features
3)I have given added permission for IIS_IUSRS to the WebConfig of my application
4)I ran this in cmd prompt: aspnet_regiis.exe -iru
C:\Windows\Microsoft.NET\Framework\v4.0.30319
5)I ran ServiceModelReg.exe -i from the “%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation” directory to register the script maps
4) and 5) I used forums.asp.net/t/1807824.aspx?WCF+Service+works+locally+but+returns+404+on+remote+server
6)Added below as per stackoverflow.com/questions/4793127/404-when-running-net-4-wcf-service-on-iis-no-svc-file
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
I've tried every solution suggested on internet. Nothing works on my local IIS7
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\Users\Julian Luwang\Documents\Visual Studio 2013\Projects\AdventureWorksEntityFramework\AdventureWorksHost\Log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<system.web>
<httpRuntime executionTimeout="1800000000" />
<compilation debug="true" targetFramework="4.5" />
<customErrors mode="On">
</customErrors>
</system.web>
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="test" helpEnabled="true" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" maxBufferSize="2147483647">
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="2147483647" maxDepth="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None"></security>
</standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
<behaviors>
<serviceBehaviors>
<!--<behavior name="Secured">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>-->
<behavior>
<serviceDebug httpHelpPageEnabled="true" httpsHelpPageEnabled="false" />
</behavior>
<behavior name="Normal">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<!-- Binding (non-secured) -->
<binding name="Normal" transferMode="Streamed" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:10:00" sendTimeout="00:03:00">
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="2147483647" maxDepth="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<!--protocol mapping added-->
<protocolMapping>
<add scheme="http" binding="webHttpBinding" bindingConfiguration="Normal" />
</protocolMapping>
</system.serviceModel>
<connectionStrings>
<add name="AdventureWorks2012Entities" connectionString="metadata=res://*/AdventureWorksEDM.csdl|res://*/AdventureWorksEDM.ssdl|res://*/AdventureWorksEDM.msl;provider=System.Data.SqlClient;provider connection string="data source=JULIAN\SQLEXPRESS;initial catalog=AdventureWorks2012;integrated security=True;trusted_connection=yes;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
<handlers>
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" />
</handlers>
<directoryBrowse enabled="true" />
<defaultDocument enabled="false">
<files>
<add value="EmployeeService" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
The Service
namespace AdventureWorksHost.Services.EmployeeService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EmployeeService : IEmployeeService
{
[WebGet(UriTemplate = "Employees/GetEmployees", ResponseFormat = WebMessageFormat.Json)]
public List<EmployeeItem> GetEmployee()
{
try
{
List<EmployeeItem> tReturn = new List<EmployeeItem>();
using (AdventureWorks2012Entities tClienEntities = new AdventureWorks2012Entities())
{
var tEmployees = (from es in tClienEntities.Employees
orderby es.JobTitle
select new
{
es.rowguid,
es.BirthDate,
es.BusinessEntityID,
es.JobTitle,
es.NationalIDNumber,
es.MaritalStatus,
es.LoginID,
}).ToList();
foreach (var tEmployee in tEmployees)
{
EmployeeItem tEmployeeItem = new EmployeeItem();
tEmployeeItem.rowguid = tEmployee.rowguid;
tEmployeeItem.BusinessEntityId = tEmployee.BusinessEntityID;
tEmployeeItem.JobTitle = tEmployee.JobTitle;
tEmployeeItem.MaritalStatus = tEmployee.MaritalStatus.ToString();
tEmployeeItem.NationalIDNumber = Int32.Parse(tEmployee.NationalIDNumber.ToString());
tEmployeeItem.BirthDate = tEmployee.BirthDate;
tEmployeeItem.LoginID = tEmployee.LoginID.ToString();
List<Person> Persons = new List<Person>();
foreach (var tPersons in (from esp in tClienEntities.People
where esp.BusinessEntityID == tEmployeeItem.BusinessEntityId
orderby esp.FirstName
select new
{
esp.rowguid,
esp.FirstName,
esp.MiddleName,
esp.LastName,
esp.PersonType,
esp.Demographics
}))
{
Persons.Add(new Person()
{
rowguid = tPersons.rowguid,
FirstName = tPersons.FirstName,
MiddleName = tPersons.MiddleName,
LastName = tPersons.LastName,
PersonType = tPersons.PersonType,
Demographics = tPersons.Demographics
});
}
tEmployeeItem.Persons = Persons;
tReturn.Add(tEmployeeItem);
}
}
return tReturn;
}
catch (FaultException ex)
{
throw (ex);
}
}
}
}
My application AdventureWorkHost look like this in my local IIS7
Application in IIS7
Resolved:
I checked the error in server logs of SQL server management studio. The error was
Message
Login failed for user 'NT AUTHORITY\NETWORK SERVICE'. Reason: Failed to open the explicitly specified database 'AdventureWorks2012'. [CLIENT: ]
So, I tried a few things.
1) Added NT AUTHORITY\NETWORK SERVICE in Security access to folder C:\inetpub\wwwroot
2)in local IIS, change identity of the application pool used by the hosted application to network service from applicationPoolIdentity
3)add new login NT AUTHORITY\NETWORK SERVICE in security of the SQL MGMT STUDIO, specify properties of the new login.
4)Set default database to your database
5)Select databases and role membership for new login as db_datareader,db_datawriter and db_owner and public
6)Set server role public and sysadmin
7)Select database->Security->User(the newly created login). Open it
8)Set owned schema as db_datareader,db_datawriter and db_owner
9)Set role membership as db_datareader,db_datawriter and db_owner
Restart local sql server and then run.

WCF REST/JSON Service UserNamePasswordValidator

I'm trying to use basic authentication with my WCF Rest/JSON service.
Therefore I've create a class which derives from "UserNamePasswordValidator" and added it to my web.config.
In IIS only Basic Authentication is enabled.
Unfortunately this class is never called. When I call a rest method in my browser the dialog for entering the username and password is shown but nothing happens after that.
Here my web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext"
value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<identity impersonate="true" />
</system.web>
<system.serviceModel>
<services>
<service name="myTimeMvc.Webservice.MyTimeRestService"
behaviorConfiguration="returnFaults">
<endpoint behaviorConfiguration="restfulBehavior"
binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="myTimeMvc.Webservice.IMyTimeRestService" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="restfulBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="returnFaults">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<serviceCredentials>
<!--<serviceCertificate findValue="MyWebSite"
storeLocation="LocalMachine"
storeName="My"
x509FindType="FindBySubjectName" />-->
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="myTimeServiceDemoa.WcfExtension.CustomUserNameValidator,TestWcfServiceAuth" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
</configuration>
Here my CustomUserNameValidator.cs
namespace myTimeServiceDemoa.WcfExtension
{
public class CustomUserNameValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException("You must provide both the username and password to access this service");
}
if (!(userName == "user1" && password == "test") && !(userName == "user2" && password == "test"))
{
throw new FaultException("Unknown Username or Incorrect Password");
}
}
}
}
UPDATE:
After two days of trying I give up now because I don't see what I may have done wrong. Seems this stuff is not working for me...
I investigated a lot and everything you need is to change Authentication of your WebApplication in IIS to "Basic" and add a custom "CustomUserNameValidator" in your web.config but this is not working!
Please correct me if I'm wrong.
My solution:
Use "Anonymous Authentication" in IIS
Use a "ServiceAuthorizationManager" and check HTTP-Headers in "CheckAccessCore"
Cheers,
Stefan

How to host workflow service (.xamlx) with net.tcp binding on IIS 7.0?

I am hosting Workflow service on iis 7.0 with net.tcp binding. My config file like as
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<appSettings>
<add key="SMTPAddress" value="000.00.0.00"/>
<add key="ToAddress" value="abc#abc.com"/>
<add key="FromAddress" value="abc#abc.com"/>
<add key="SMTPUserName" value="abc#abc.com"/>
<add key="SMTPPassword" value ="abc#abc.com"/>
</appSettings>
<connectionStrings>
<add name="RewindConnectionString" connectionString="Data Source=xxx;User Id=xxx;Password=xxx;Connection Timeout=5" providerName="Oracle.DataAccess.Client" />
</connectionStrings>
<system.serviceModel>
<tracking>
<profiles>
<trackingProfile name="Sample Tracking Profile">
<workflow activityDefinitionId="*">
<workflowInstanceQueries>
<workflowInstanceQuery>
<states>
<state name="*"/>
</states>
</workflowInstanceQuery>
</workflowInstanceQueries>
<activityStateQueries>
<activityStateQuery activityName="*">
<states>
<state name="*"/>
</states>
<variables>
<variable name="*"/>
</variables>
</activityStateQuery>
</activityStateQueries>
<activityScheduledQueries>
<activityScheduledQuery activityName="*" childActivityName="*"/>
</activityScheduledQueries>
<faultPropagationQueries>
<faultPropagationQuery faultSourceActivityName="*" faultHandlerActivityName="*"/>
</faultPropagationQueries>
<customTrackingQueries>
<customTrackingQuery name="*" activityName="*"/>
</customTrackingQueries>
</workflow>
</trackingProfile>
</profiles>
</tracking>
<services>
<service name="RewindTest" behaviorConfiguration="RewindTest_Behavior">
<endpoint address="RewindTest"
binding="netTcpBinding" contract="IRewindTestService" name="RewindTestNetTcpEndPoint" bindingConfiguration="RewindTestBinding" />
<endpoint address="wce"
binding="netTcpBinding" kind="workflowControlEndpoint" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:9095/Service.Workflow.RewindTest/RewindTest" />
</baseAddresses>
</host>
<endpoint address="mex"
binding="mexTcpBinding"
name="MEX"
contract="IMetadataExchange" />
</service>
</services>
<bindings>
<netTcpBinding>
<binding portSharingEnabled="true" name="RewindTestBinding" closeTimeout="00:10:00" openTimeout="00:10:00"
sendTimeout="00:10:00" maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<standardEndpoints>
<workflowControlEndpoint>
<standardEndpoint/>
</workflowControlEndpoint>
</standardEndpoints>
<extensions>
<behaviorExtensions>
<add name="oracleInstanceStore" type="Devart.Data.Oracle.Activities.Configuration.OracleInstanceStoreElement, Devart.Data.Oracle.WorkflowFoundation" />
<add name="oracleTracking" type="Devart.Data.Oracle.Activities.Configuration.OracleTrackingElement, Devart.Data.Oracle.WorkflowFoundation" />
</behaviorExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior name="RewindTest_Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false"/>
<!-- 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"/>
<oracleTracking
connectionString="User Id=xxx;Password=xxx;Server=xxx;"
profileName="Sample Tracking Profile" />
<oracleInstanceStore
connectionString="User Id=xxx;Password=xxx;Server=xxx;"
instanceEncodingOption="None"
instanceCompletionAction="DeleteNothing"
instanceLockedExceptionAction="NoRetry"
hostLockRenewalPeriod="00:00:30"
runnableInstancesDetectionPeriod="00:00:05" />
<workflowIdle timeToUnload="0"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Now my issue is i am unable to generate proxy through net.tcp binding but i can generate it through http. http://testsrv.com/RewindService/RewindTest.xamlx?wsdl. then i am unable to call receive operation method. Although it is workking fine with local console Host.
As we know that workflow service is similar to wcf service. So I decided to reconsider my deployment steps. I found a very good link about it and follow and check each and every step carefully and able to resolved my problem.
http://galratner.com/blogs/net/archive/2010/10/08/setting-up-a-nettcpbinding-enabled-wcf-service-in-iis-7.aspx
My configuration is ok and updated the tcp port no. it works like a charm.

WCF Session ASP.NET Hosting Issue

I am building a WCF service that speaks to an existing application, and this application requires access to ASP.NET sessions - the ability to see sessions is a requirement I cannot get around.
I built the WCF project - and have the following setting in App.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
I also included an interface and an implementation of the service in the file. In front of the implementation I have:
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Required)]
public class SearchService : ISearchServiceInterface
{
This is a REST service, so my interface starts like:
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ISearchServiceInterface
{
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
string LoginToWebService_POST(Altec.Framework.Authorization auth);
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
string GetTopLevelFolderName_POST();
The service itself is hosted in another web application - in a SearchService.svc file which has this:
<%#ServiceHost language=c# Debug="true" Service="Altec.UI.Web.SearchService.SearchService" %>
and I added this to the web.config of the hosting application:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
I believe I did all the right steps - and yet when I try to run the web application I get this error:
"
System.InvalidOperationException: This service requires ASP.NET
compatibility and must be hosted in IIS. Either host the service in
IIS with ASP.NET compatibility turned on in web.config or set the
AspNetCompatibilityRequirementsAttribute.AspNetCompatibilityRequirementsMode
property to a value other than Required. at
System.ServiceModel.Activation.AspNetEnvironment.ValidateCompatibilityRequirements(AspNetCompatibilityRequirementsMode
compatibilityMode) at
System.ServiceModel.Activation.AspNetCompatibilityRequirementsAttribute.System.ServiceModel.Description.IServiceBehavior.Validate(ServiceDescription
description, ServiceHostBase serviceHostBase) at
System.ServiceModel.Description.DispatcherBuilder.ValidateDescription(ServiceDescription
description, ServiceHostBase serviceHost) at
System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription
description, ServiceHostBase serviceHost) at
System.ServiceModel.ServiceHostBase.InitializeRuntime() at
System.ServiceModel.ServiceHostBase.OnBeginOpen() at
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at System.ServiceModel.Channels.CommunicationObject.Open()
at Microsoft.Tools.SvcHost.ServiceHostHelper.OpenService(ServiceInfo
info)"
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<appSettings>
<!-- database connection details -->
</appSettings>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<pages>
<controls>
<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"/>
</controls>
</pages>
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="1048576"/>
</webServices>
</scripting>
</system.web.extensions>
<location path="Scripts">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="Content">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="jQuery-UI-layout.css">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ISearchServiceInterface" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None" realm=""/>
<message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://vmwarren27dev.altec-wa.com/Altec.UI.Web.Portal/SearchService.svc/WCPService" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISearchServiceInterface" contract="SearchService.ISearchServiceInterface" name="WSHttpBinding_ISearchServiceInterface">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
<services>
<service name="Altec.UI.Web.SearchService.SearchService">
<endpoint address="RESTService" binding="webHttpBinding" behaviorConfiguration="json" contract="Altec.UI.Web.SearchService.ISearchServiceInterface">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<endpoint address="WCPService" binding="wsHttpBinding" contract="Altec.UI.Web.SearchService.ISearchServiceInterface">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="json">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="AjaxControlToolkit" publicKeyToken="28f01b0e84b6d53e" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.51116.0" newVersion="4.1.51116.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
You mentioned App.config - it sounds like your service is a WCF Service Library, that you're hosting under IIS. If that's the case, you need to copy the WCF configuration section from the App.config to the Web.config of the IIS application that is hosting your service.
Libraries don't use config files - they use the config file of the calling application.

Resources