WCF Rest Service broken after server restart - wcf

I made a WCF Rest Service and attached it to IIS 7 on my server and it worked great. Suddenly, we had a hard drive failure and the guys who're supposed to manage the backups didn't back up anything, so we lost all our stuff on the server.
So I go about setting everything back up, and I put all the stuff on IIS. We have another WCF Rest Service that does a lot of stuff the one I made does, including a couple of the same methods for authentication and such. But now it seems that mine won't work. Our website works and our other web service works, but not this one, and I've no idea why? I set them up the exact same and I don't think I changed anything when I did it initially.
The help reference pages work, but when calling the method, I get
"The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service."
I'm using the same methods as before, calling them with the same arguments, this happens for every method, regardless of GET or POST. I've used a REST extension thing in chrome to call it and the mobile app that I usually use to call it, as well as the browser and they all come up with the same error.
Here's the web.config file for it (I've tried adding a few things found on stackoverflow to get to the problem, but it's not done anything, really).
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel >
<behaviors>
<serviceBehaviors>
<behavior name="DataServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings >
<!-- pick whichever binding you want .... -->
<basicHttpBinding>
<!-- binding configuration with a name -->
<binding name="ExtendedMaxSize"
maxBufferSize="52428800" maxReceivedMessageSize="52428800" >
<readerQuotas maxDepth="52428800" maxStringContentLength="52428800"
maxArrayLength="52428800" maxBytesPerRead="52428800" maxNameTableCharCount="52428800" />
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="52428800" maxBufferSize="52428800" maxBufferPoolSize="52428800" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
After turning tracing on, got this error from the viewer:
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"><System
xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"><EventID>131076</EventID><Type>3</Type><SubType Name="Error">0</SubType><Level>2</Level><TimeCreated SystemTime="2014-03-27T12:15:47.5749853Z" /><Source Name="System.ServiceModel" /><Correlation ActivityID="{54672f7e-5a71-4dda-92a3-f07f7c94ccb9}" /><Execution ProcessName="w3wp" ProcessID="20820" ThreadID="9" /><Channel /><Computer>OHS-VMHOST-NEW</Computer></System><ApplicationData><TraceData><DataItem><TraceRecord Severity="Error" Channel="Operational" xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord"><TraceIdentifier>http://msdn.microsoft.com/en-GB/library/System.ServiceModel.Diagnostics.TraceHandledException.aspx</TraceIdentifier><Description>Handling an exception. Exception details: System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult& result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
at SyncInvokeGetProjectData(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</Description><AppDomain>/LM/W3SVC/1/ROOT/mobileassessor-1-130403961472161807</AppDomain><Exception><ExceptionType>System.FormatException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).</Message><StackTrace> at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult&amp; result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult&amp; result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
at SyncInvokeGetProjectData(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><ExceptionString>System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult&amp; result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult&amp; result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
at SyncInvokeGetProjectData(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</ExceptionString></Exception></TraceRecord></DataItem></TraceData></ApplicationData></E2ETraceEvent>
As requested, my GetProjectData method (And no, it isn't managing to write anything to my event log):
/// <summary>
///
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
[WebGet(UriTemplate = "GetProjectData/{token}", ResponseFormat = WebMessageFormat.Json)]
public GetProjectContainerResult GetProjectData(string token)
{
WriteLog("Getting project data...");
GetProjectContainerResult result = new GetProjectContainerResult();
ProjectContainer container = new ProjectContainer();
MobileAssessorAuthenticationResults authResult = ValidateToken(new Guid(token));
if (authResult == MobileAssessorAuthenticationResults.Success)
{
container.jobs = getJobs(token);
container.buildings = getBuildings();
container.floors = getFloors();
container.locations = getLocations();
result.ReturnValue = container;
result.Result = MobileAssessorOperationResults.Success;
}
else
{
switch (authResult)
{
case MobileAssessorAuthenticationResults.Error:
result.Result = MobileAssessorOperationResults.Error;
result.ResultDescription = "An error occured.";
result.ReturnValue = new ProjectContainer();
break;
case MobileAssessorAuthenticationResults.Expired:
result.Result = MobileAssessorOperationResults.Failed;
result.ResultDescription = "The specified token has expired.";
result.ReturnValue = new ProjectContainer();
break;
case MobileAssessorAuthenticationResults.Invalid:
result.Result = MobileAssessorOperationResults.Failed;
result.ResultDescription = "The specified token is not valid.";
result.ReturnValue = new ProjectContainer();
break;
}
}
return result;
}

Looking at the stack trace from your log, I think you are having issues parsing a GUID in MobileAssessorAPIService.GetProjectData method
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult&amp; result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult&amp; result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
I would recommend that you put a break point in this method and attach a debugger to your REST service.
Based on the code you posted, the suspected line is
MobileAssessorAuthenticationResults authResult = ValidateToken(new Guid(token));
if you are not able to remotely debug this, I would recommend that you add logging just before this line to log the value of token. something like
logger.Log("paramater token = " + token);
Alternately, use wireshark to check the value of the token. once you extract the value of that guid, validate it online at http://guid.us/Test/GUID

Related

WCF customUserNamePasswordValidatorType error - Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies

I have created a simply WCF web service and require WCF Security with username/password added to the service and have read through the following MS documentation https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-a-custom-user-name-and-password-validator to try and do so.
However, I am getting the error below when I run the project and go to http://localhost:50533/Service.svc:
Server Error in '/' Application.
Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'CustomUserNameValidator' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = CustomUserNameValidator
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: CustomUserNameValidator | Domain ID: 6
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/
LOG: Initial PrivatePath = C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\web.config
LOG: Using host configuration file: C:\Users\xxxx\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.EXE.
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +71
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +41
System.Type.GetType(String typeName, Boolean throwOnError) +35
System.ServiceModel.Configuration.UserNameServiceElement.ApplyConfiguration(UserNamePasswordServiceCredential userName) +356
System.ServiceModel.Configuration.ServiceCredentialsElement.ApplyConfiguration(ServiceCredentials behavior) +128
System.ServiceModel.Configuration.ServiceCredentialsElement.CreateBehavior() +165
System.ServiceModel.Description.ConfigLoader.LoadBehaviors(ServiceModelExtensionCollectionElement`1 behaviorElement, KeyedByTypeCollection`1 behaviors, Boolean commonBehaviors) +204
System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress, Boolean skipHost) +13502205
System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection) +74
System.ServiceModel.ServiceHostBase.ApplyConfiguration() +188
System.ServiceModel.ServiceHost.ApplyConfiguration() +65
System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses) +188
System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses) +49
System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses) +153
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) +34
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +538
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1489
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +53
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +666
[ServiceActivationException: The service '/Service.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified..]
System.Runtime.AsyncResult.End(IAsyncResult result) +513025
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +182
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +12
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +161
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +128
I have noticed this error only appears due to adding the following into my Web.Config file
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
I've modified the value in customUserNamePasswordValidatorType numerous times to try and fix it but the error still comes up or a similar one.
See below for the full Web.Config file.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<pages>
<namespaces>
<add namespace="System.Runtime.Serialization"/>
<add namespace="System.ServiceModel"/>
<add namespace="System.ServiceModel.Web"/>
</namespaces>
</pages>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Binding1">
<security mode="Transport">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</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"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</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"/>
</system.webServer>
</configuration>
The Code is simply the default WCF Service code you get out of the box when creating a new WCF Service project in Visual Studio and I've just added a new CustomUserNameValidator class.
If you want to see this class, here is the code for it:
Imports System.IdentityModel.Selectors
Public Class CustomUserNameValidator
Inherits UserNamePasswordValidator
Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
If userName Is Nothing OrElse password Is Nothing Then
Throw New ArgumentNullException()
End If
If Not (userName = "user" AndAlso password = "pass123") Then
Throw New FaultException("Unknown Username or Incorrect Password")
End If
End Sub
End Class
Also, this is all that shows in Properties for the file.
If you can please help with the error, that would be very much appreciated.
You must to be sure that the “Build Action” on the “CustomUserNameValidator.vb” Properties is set to “Compile”.
It seems to be set on “Content” based on what you are describing.
The image shows how you can do that or take a look here:
https://learn.microsoft.com/en-us/visualstudio/ide/build-actions?view=vs-2022
The reason I was getting the problem above was because I needed to set this in the web.config
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator, App_Code" />
</serviceCredentials>
When I went to the following path on my machine, the only dll was App_Code.tjgywzog.dll so figured the assembly is just App_Code and then it just has to use the class name CustomUserNameValidator since my code is not using namespaces.

wcf data service can work on iisexpress, but not in iis

I wrote a very simple WCF data service. But I find that can't work when I deploy on IIS7.5. It just only can work on IIS Express.
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class WcfDataService : DataService<ConfigurationDataEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.UseVerboseErrors = true;
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
// config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
This is webconfig file
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework5" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ConfigurationDataEntities" connectionString="metadata=res://*/ConfigurationDataModel.csdl|res://*/ConfigurationDataModel.ssdl|res://*/ConfigurationDataModel.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="data source=|DataDirectory|\ConfigurationData.sdf;password=123;persist security info=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<entityFramework5>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework5>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
</configuration>
This is the error message:
The server encountered an error processing the request. See server logs for more details.
在 System.Data.Entity.DbContext..ctor(String nameOrConnectionString) 在 WcfDataServiceTest.ConfigurationDataEntities..ctor() 位置 c:\Projects\WcfDataServiceTest\WcfDataServiceTest\ConfigurationDataModel.Context.cs:行号 18 在 invoke_constructor() 在 System.Data.Services.DataService1.CreateDataSourceInstance() 在 System.Data.Services.DataService1.CreateMetadataAndQueryProviders(IDataServiceMetadataProvider& metadataProviderInstance, IDataServiceQueryProvider& queryProviderInstance, BaseServiceProvider& builtInProvider, Object& dataSourceInstance) 在 System.Data.Services.DataService1.CreateProvider() 在 System.Data.Services.DataService1.HandleRequest() 在 System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) 在 SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) 在 System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) 在 System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) 在 System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
Anyone can help me?
WCF helps you:
See server logs for more details.
Configure tracing and see where the exception occurs. Since it's happening in the DbContext constructor, I assume there's something with database access. Check the account the application pool runs under and verify this account can access the database.

"No destination configuration registered" - WCF/SAP integration using SAP nCo3 (SAP .NET Connectior 3.0)

When I try to call a WCF service I developed I get this error message: "Method or operation is not implemented".
Let me explain the scenario I'm facing and them I'll give you more details, the code and etc:
I'm developing a WCf service in .NET framework 4.0 in a Windows 8/Visual Studio 2012 machine.
The WCF service will be accessed from a mobile application developed in .NET compact framework 2.0 (Dev environment: a Virtual Machine running Windows XP service pack 3, Visual Studio 2008, Windows Mobile 6.1 Professional Emulator).
The WCF service is using the SAP .NET Conector (SAPnCO) version 3.0.
When I run the service using VS integrated IIS or IIS8, everything goes fine: I can test the service, access it from a test console application and can access it from Windows Mobile Emulator.
However, we where about to start some preliminar tests with the final users and we still didn`t have a proper server to deploy the WCF application, so I had to make a contingency server using Windows XP and IIS express 7.5 (I was not able to make it work on IIS 5.1).
I know that IIS Express is for local access only, but I followed this tutorial to open ti to the LAN: TUTORIAL.
Doing so I can acess the service signature via browser and see the WSDL file.
Everytime i try to acess the service I get the error message "Method or operation is not implemented". I`ve been looking for some similar problem over the internet for the past 4 hours without success.
Here`s what I managed to do so far:
Host a default WCF sample service on IIS Express 7.5 and use the service remotely: ok;
Reduce the scope of the original service to the minimal only: still get the same error;
So, I still don't know what can be causing this or how to solve it. I kindly request for your help, please!
Here`s my code:
WEB.CONFIG
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="SAP.Middleware.Connector">
<sectionGroup name="ClientSettings">
<section name="DestinationConfiguration" type="SAP.Middleware.Connector.RfcDestinationConfiguration, sapnco"/>
</sectionGroup>
</sectionGroup>
</configSections>
<SAP.Middleware.Connector>
<ClientSettings>
<DestinationConfiguration>
<destinations>
<add NAME="QA" USER="XX" PASSWD="XX" CLIENT="XX" LANG="XX" ASHOST="XX" SYSNR="XX" MAX_POOL_SIZE="XX" IDLE_TIMEOUT="XX"/>
</destinations>
</DestinationConfiguration>
</ClientSettings>
</SAP.Middleware.Connector>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings/>
<system.web>
<compilation targetFramework="4.0" debug="true"/>
<httpRuntime/>
</system.web>
<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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</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"/>
</system.webServer>
</configuration>
SERVICE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using SAP.Middleware.Connector;
namespace WCFCriarOT
{
public class Service1 : IService1
{
public string CriarOT(int areaSelecionada, int nlenr, string codMaterial, int qtdMAterial)
{
try
{
string vltyp = "", vlpla = "";
switch (areaSelecionada)
{
case 1:
vltyp = "902";
vlpla = "GR-ZONE";
break;
case 3:
vltyp = "901";
vlpla = "GFI-ZONE";
break;
case 4:
vltyp = "904";
vlpla = "DEVOLUCAO";
break;
default:
break;
}
RfcDestination SapRfcDestination = RfcDestinationManager.GetDestination("QA");
RfcRepository SapRfcRepository = SapRfcDestination.Repository;
IRfcFunction FCriarOT = SapRfcRepository.CreateFunction("ZWM001");
FCriarOT.SetValue("I_LGNUM", "WM1");
FCriarOT.SetValue("I_BWLVS", "999");
FCriarOT.SetValue("I_MATNR", codMaterial);
FCriarOT.SetValue("I_WERKS", "120");
FCriarOT.SetValue("I_LGORT", "0001");
FCriarOT.SetValue("I_ANFME", qtdMAterial);
FCriarOT.SetValue("I_SQUIT", "");
FCriarOT.SetValue("I_VLTYP", vltyp);
FCriarOT.SetValue("I_VLPLA", vlpla);
FCriarOT.SetValue("I_VLENR", "");
FCriarOT.SetValue("I_NLTYP", "");
FCriarOT.SetValue("I_NLPLA", "");
FCriarOT.SetValue("I_NLENR", nlenr.ToString().PadLeft(20, '0'));
FCriarOT.SetValue("I_BNAME", "PAGOTR"); // receber os dados do login posteriormente
FCriarOT.Invoke(SapRfcDestination);
if (Convert.ToInt32(FCriarOT.GetValue("E_RETURN")) == 1)
{
IRfcTable RfcReturn = FCriarOT.GetTable("T_MSG");
RfcReturn.CurrentIndex = 0;
return "1";
}
else
{
return "0";
}
}
catch (Exception ex)
{
throw new NotImplementedException();
}
}
}
SERVICE SIGNATURE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WCFCriarOT
{
[ServiceContract]
public interface IService1
{
// Contrato para a operação "Criar OT"
[OperationContract]
string CriarOT(int areaSelecionada, int nlenr, string codMaterial, int qtdMAterial);
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
}
Exception
System.ServiceModel.FaultException`1 was unhandled
HResult=-2146233087
Message=O método ou a operação não está implementada.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at testeDoTeste1.ServiceReference1.IService1.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial)
at testeDoTeste1.ServiceReference1.Service1Client.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Service References\ServiceReference1\Reference.cs:line 119
at testeDoTeste1.Program.Main(String[] args) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
If I have failed in provide all necessary information, please, let me know: I will provide anything I can. I really need and apretiate all your help! Tks a lot!
--------------
UPDATE 1
Since the WEB.CONFIG file is the only piece of the service that is edited to make the WCF service work with IIS Express I think this can (evetually) be the source of trouble. I`m posting the original WEB.CONFIG file, without the edits hoping that this can help someone spot the problem!
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="SAP.Middleware.Connector">
<sectionGroup name="ClientSettings">
<section name="DestinationConfiguration" type="SAP.Middleware.Connector.RfcDestinationConfiguration, sapnco"/>
</sectionGroup>
</sectionGroup>
</configSections>
<SAP.Middleware.Connector>
<ClientSettings>
<DestinationConfiguration>
<destinations>
<add NAME="QA" USER="XX" PASSWD="XX" CLIENT="XX" LANG="XX" ASHOST="XX" SYSNR="XX" MAX_POOL_SIZE="XX" IDLE_TIMEOUT="XX"/>
</destinations>
</DestinationConfiguration>
</ClientSettings>
</SAP.Middleware.Connector>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings/>
<system.web>
<compilation targetFramework="4.0" debug="true"/>
<httpRuntime/>
</system.web>
<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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</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"/>
</system.webServer>
</configuration>
--------------
UPDATE 2
Found a new error, but it`s still fuzzy to me: "{"Cannot get destination QA -- no destination configuration registered"}". This destination works fine in dev, so why it is not working on IIS Express?
Anyways, here`s the complete exception:
System.ServiceModel.FaultException`1 was unhandled
HResult=-2146233087
Message=Cannot get destination QA -- no destination configuration registered
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at testeDoTeste1.ServiceReference1.IService1.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial)
at testeDoTeste1.ServiceReference1.Service1Client.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Service References\ServiceReference1\Reference.cs:line 119
at testeDoTeste1.Program.Main(String[] args) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
--------------
I have found, this exception occurs if sapnco assembly is not loaded. Try to set referenced SAP assemblies to Copy local: True.
It is not ideal solution, but it has worked for me well.
I resolved it by moving the configSections' section to the top of the app.config. Maybe the 'configSections' must be the first child section of configuration.
See here too:
Parameter 'sectionGroupName' is invalid

WCF Net.TCP service throwing obscure errors

I am trying to enable an additional net.tcp endpoint (which uses Username authentication) for an existing WCF service. The service is hosted in IIS7.
Executing a client against the service returns an error that the socket connection was aborted. Enabling tracing against the service reveals the following exception is thrown:
System.ArgumentOutOfRangeException
The value of this argument must be positive.
Parameter name: maxAccepts
Actual value was 0.
I'm confused, because as best I can tell port sharing should be disabled by the configuration (see below), but it's still calling through the port sharing code (again, as best I can tell). In any case, I can't find any way to specify this maxAccepts value; Google doesn't know anything about it, and the maxPendingAccepts value doesn't seem to do it. How do I resolve the error?
The service's config file contains the following for the net.tcp endpoint:
<bindings>
<customBinding>
<binding name="netTcp">
<security authenticationMode="UserNameOverTransport" />
<windowsStreamSecurity />
<tcpTransport portSharingEnabled="false" listenBacklog="10" maxPendingAccepts="10" maxPendingConnections="10" />
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="netTcp">
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceMetadata/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Asi.Soa.ServiceModelEx.NullUserNamePasswordValidator, Asi.Soa.ServiceModelEx" />
<clientCertificate>
<authentication certificateValidationMode="None"/>
</clientCertificate>
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="Asi.Soa.ServiceModelEx.ClaimsAuthorizationPolicy, Asi.Soa.ServiceModelEx" />
</authorizationPolicies>
</serviceAuthorization>
</behavior>
</serviceBehaviors>
</behaviors>
The full exception stack trace is:
System.ServiceModel.Channels.ConnectionAcceptor..ctor(IConnectionListener listener, Int32 maxAccepts, Int32 maxPendingConnections, ConnectionAvailableCallback callback, ErrorCallback errorCallback)
System.ServiceModel.Channels.ConnectionDemuxer..ctor(IConnectionListener listener, Int32 maxAccepts, Int32 maxPendingConnections, TimeSpan channelInitializationTimeout, TimeSpan idleTimeout, Int32 maxPooledConnections, TransportSettingsCallback transportSettingsCallback, SingletonPreambleDemuxCallback singletonPreambleCallback, ServerSessionPreambleDemuxCallback serverSessionPreambleCallback, ErrorCallback errorCallback)
System.ServiceModel.Channels.SharedTcpTransportManager.CreateConnectionDemuxer()
System.ServiceModel.Channels.SharedTcpTransportManager.OnDuplicatedVia(Uri via, Int32& connectionBufferSize)
System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.HandleOnVia(DuplicateContext duplicateContext)
System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.System.ServiceModel.Activation.IConnectionDuplicator.BeginDuplicate(DuplicateContext duplicateContext, AsyncCallback callback, Object state)
AsyncInvokeBeginBeginDuplicate(Object , Object[] , AsyncCallback , Object )
System.ServiceModel.Dispatcher.AsyncMethodInvoker.InvokeBegin(Object instance, Object[] inputs, AsyncCallback callback, Object state)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Dispatch(MessageRpc& rpc, Boolean isOperationContextSet)
System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(IAsyncResult result)
System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.OnReceiveComplete(Object state)
System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
System.ServiceModel.Channels.TracingConnection.WaitCallback(Object state)
System.ServiceModel.Channels.PipeConnection.OnAsyncReadComplete(Boolean haveResult, Int32 error, Int32 numBytes)
System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Edit: I have installed the non-HTTP WCF activation components, run ServiceModelReg.exe, added net.tcp and net.pipe to the list of enabled protocols in IIS Manager, etc. No joy.
I've also written a quick Windows Service to host the service (not the ideal long-term solution for us), and the Net TCP connection works fine there, so it doesn't appear to be anything in my configuration or code, which means something isn't right in/with IIS. Does the app pool for the application have to be running in Integrated mode? I tried it both ways, it didn't seem to make a difference, but our app currently is installed in Classic mode.
As best I can determine, the problem is simply that .NET does not like hosting two services in the same IIS application when one is a Soap11 endpoint and one is a NetTcp endpoint. Removing the Soap11 endpoint allows the NetTcp endpoint to work without error.
We've moved to a model where we are using a Windows Service to host the NetTcp endpoint and left the Soap11 endpoint in IIS.
If anyone figures out how to host both a NetTcp and Soap11 service in the same application in IIS, I'd love to hear about it.
Net.tcp does not work on IIS7 out-of-the-box, there are a number of things that need to be activated.
See: http://labs.episerver.com/en/Blogs/Paul-Smith/Dates/2008/6/Hosting-non-HTTP-based-WCF-applications-in-IIS7/

Wcf in Medium / Partial Trust (Mosso) - odd problem / config error

Whew! Ok… I solved my Wcf / Linq errors (and learned a lot – a series of blog posts will follow next weak). Now I need to deploy. We run on the Mosso / Rackspace cloud, and for the moment that environment runs in a partial trust environment.
To make it simple, I added a method to my Wcf service that does just about NOTHING.
public string Echo(string what)
{
return what;
}
I built it all, and shipped it to the test server with the following Web.Config (relevant section only)… yes, I will need to add security obviously before exposing the dangerous methods, but for now I jsut want the anonymous stuff running :)
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicAnonymous">
<security mode="None"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="FooBar.Backend.Web.Services.CoreDataWcfServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="FooBar.Backend.Web.Services.CoreDataWcfServiceBehavior"
name="FooBar.Backend.Web.Services.CoreDataWcfService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicAnonymous" contract="FooBar.Backend.Web.Services.ICoreDataWcfService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
<baseAddressPrefixFilters>
<add prefix="http://backend.FooBar.com"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>
</system.serviceModel>
So, off I go to call it in the simplest way I can with a console application. i add the service reference and it adds fine. Then I call it (I took inactive code for brevity)…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreWcfHarness.CoreDataServiceReference;
namespace CoreWcfHarness
{
class Program
{
static void Main(string[] args)
{
var context = new CoreDataWcfServiceClient();
var echoval = context.Echo("Hello World!");
Console.WriteLine(String.Format("{0}\n", echoval));
Console.ReadKey();
}
}
}
And blammo. I get hit with an exception.
System.ServiceModel.FaultException`1 was unhandled
Message="Request failed."
Source="mscorlib"
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at CoreWcfHarness.CoreDataServiceReference.ICoreDataWcfService.Echo(String what)
at CoreWcfHarness.CoreDataServiceReference.CoreDataWcfServiceClient.Echo(String what) in C:\PathToProject\corewcfharness\service references\coredataservicereference\reference.cs:line 1890
at CoreWcfHarness.Program.Main(String[] args) in C:\PathToProject\CoreWcfHarness\Program.cs:line 42
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
This is about as simple as it gets. Anyone familiar with medium trust environments and / or good with a stack trace?
Thanks!
"Request Failed" could be a number of things.
It looks like the most probable reason is that the request is not reaching the server. You should check the server logs to make sure that the request is being sent to the correct place.