Accessing stateless service via ServiceProxy fails + ASP.NET 5 Web API project throws Health State error
<p>I'm new to microsoft azure service fabric. For my master's degree I have to develop a microservice-approach prototype in service fabric. After hours of researching I am still not getting my issue(s) solved.</p>

<p>I want to access my (in a local fabric cluster deployed) stateless service in a web front-end like in <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-add-a-web-frontend/" rel="noreferrer">https://azure.microsoft.com/en-us/documentation/articles/service-fabric-add-a-web-frontend/</a>. The simplest way for doing that is by adding an ASP .NET 5 Web Api project to the Service Fabric application and make a <code>ServiceProxy</code> method call in the <code>ValuesController</code>. So I added this code to my solution:</p>

<p><strong>ValuesController.cs:</strong></p>

<pre class="lang-cs prettyprint-override"><code>[Route("api/[controller]")]
public class ValuesController : Controller
{
  // GET api/values/IObject
  [HttpGet("{interfaceName}")]
  public async Task&lt;string&gt; Get(string interfaceName)
  {
    var serviceName = "fabric:/DataServiceFabric/MasterDataMService";
    var masterDataService = ServiceProxy.Create&lt;IMasterDataMService&gt;(new Uri(serviceName));
    var result = await masterDataService.GetMasterDataByName(interfaceName);
    return result.Content;
  }
}
</code></pre>

<p>After a F5-deploy my browser doesn't automatically navigate to my web front-end. By looking into the Service Fabric Explorer my ASP .NET 5 application throws a Health State error:</p>

<pre><code>Kind        Health State  Description
=============================================================================
Partitions  Error         Unhealthy partitions: 100% (1/1), MaxPercentUnhealthyPartitionsPerService=0%.
Partition   Error         Unhealthy partition: PartitionId='413...', AggregatedHealthState='Error'.
Event       Error         Error event: SourceId='System.FM', Property='State'. Partition is below target replica or instance count.
</code></pre>

<p>After this <a href="https://stackoverflow.com/questions/34892366/partition-is-below-target-replica-or-instance-count-error-after-deploying-serv">this</a> question the <em>"Partition is below target replica or instance count"</em> indicates that a unhandled exception in my service is preventing it from starting. But I'm not able to find a stack strace in my Service Fabric Explorer to debug this failure. This is my <code>ServiceManifest.xml</code> of my ASP .NET web service:</p>

<p><strong>ServiceManifest.xml (Web1):</strong></p>

<pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;ServiceManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Name="Web1" Version="1.0.0" xmlns="http://schemas.microsoft.com/2011/01/fabric"&gt;
   &lt;ServiceTypes&gt;
      &lt;StatelessServiceType ServiceTypeName="Web1Type"&gt;
         &lt;Extensions&gt;
            &lt;Extension Name="__GeneratedServiceType__"&gt;
               &lt;GeneratedNames xmlns="http://schemas.microsoft.com/2015/03/fabact-no-schema"&gt;
                  &lt;DefaultService Name="Web1Service" /&gt;
                  &lt;ServiceEndpoint Name="Web1TypeEndpoint" /&gt;
               &lt;/GeneratedNames&gt;
            &lt;/Extension&gt;
         &lt;/Extensions&gt;
      &lt;/StatelessServiceType&gt;
   &lt;/ServiceTypes&gt;
   &lt;CodePackage Name="C" Version="1.0.0"&gt;
      &lt;EntryPoint&gt;
         &lt;ExeHost&gt;
            &lt;Program&gt;approot\runtimes\dnx-clr-win-x64.1.0.0-rc1-update1\bin\dnx.exe&lt;/Program&gt;
            &lt;Arguments&gt;--appbase approot\src\Web1 Microsoft.Dnx.ApplicationHost Microsoft.ServiceFabric.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener&lt;/Arguments&gt;
            &lt;WorkingFolder&gt;CodePackage&lt;/WorkingFolder&gt;
            &lt;ConsoleRedirection FileRetentionCount="5" FileMaxSizeInKb="2048" /&gt;
         &lt;/ExeHost&gt;
      &lt;/EntryPoint&gt;
   &lt;/CodePackage&gt;
   &lt;Resources&gt;
      &lt;Endpoints&gt;
         &lt;Endpoint Name="Web1TypeEndpoint" Protocol="http" Type="Input" Port="80" /&gt;
      &lt;/Endpoints&gt;
   &lt;/Resources&gt;
&lt;/ServiceManifest&gt;
</code></pre>

<p>And here my <code>ApplicationManifest.xml</code> of my service fabric solution:</p>

<p><strong>ApplicationManifest.xml:</strong></p>

<pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;ApplicationManifest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationTypeName="DataServiceFabricType" ApplicationTypeVersion="1.0.0" xmlns="http://schemas.microsoft.com/2011/01/fabric"&gt;
   &lt;Parameters&gt;
      &lt;Parameter Name="ActorTestServiceActorService_PartitionCount" DefaultValue="10" /&gt;
      &lt;Parameter Name="MasterDataMService_InstanceCount" DefaultValue="-1" /&gt;
   &lt;/Parameters&gt;
   &lt;ServiceManifestImport&gt;
     &lt;ServiceManifestRef ServiceManifestName="Web2Pkg" ServiceManifestVersion="1.0.0" /&gt;
     &lt;ConfigOverrides /&gt;
   &lt;/ServiceManifestImport&gt;
   &lt;ServiceManifestImport&gt;
      &lt;ServiceManifestRef ServiceManifestName="Web1" ServiceManifestVersion="1.0.0" /&gt;
   &lt;/ServiceManifestImport&gt;
   &lt;ServiceManifestImport&gt;
      &lt;ServiceManifestRef ServiceManifestName="ActorTestServicePkg" ServiceManifestVersion="1.0.0" /&gt;
   &lt;/ServiceManifestImport&gt;
   &lt;ServiceManifestImport&gt;
      &lt;ServiceManifestRef ServiceManifestName="MasterDataMServicePkg" ServiceManifestVersion="1.0.0" /&gt;
      &lt;ConfigOverrides /&gt;
   &lt;/ServiceManifestImport&gt;
   &lt;DefaultServices&gt;
      &lt;Service Name="Web1Service"&gt;
         &lt;StatelessService ServiceTypeName="Web1Type"&gt;
            &lt;SingletonPartition /&gt;
         &lt;/StatelessService&gt;
      &lt;/Service&gt;
      &lt;Service Name="ActorTestServiceActorService" GeneratedIdRef="761ee3cf-5a3a-49d8-9c57-aa3480d1acf1"&gt;
         &lt;StatelessService ServiceTypeName="ActorTestServiceActorServiceType"&gt;
            &lt;UniformInt64Partition PartitionCount="[ActorTestServiceActorService_PartitionCount]" LowKey="-9223372036854775808" HighKey="9223372036854775807" /&gt;
         &lt;/StatelessService&gt;
      &lt;/Service&gt;
      &lt;Service Name="MasterDataMService"&gt;
         &lt;StatelessService ServiceTypeName="MasterDataMServiceType" InstanceCount="[MasterDataMService_InstanceCount]"&gt;
            &lt;SingletonPartition /&gt;
         &lt;/StatelessService&gt;
      &lt;/Service&gt;
   &lt;/DefaultServices&gt;
&lt;/ApplicationManifest&gt;
</code></pre>

<p>So I created a new solution with an ASP.NET 5 web application and the same <code>ValuesController.cs</code>. I ensured my stateless service is running on my local cluster and than I started my new web application. After calling the GET-Method in my Controller I got the following exception:</p>

<pre><code>Exception thrown: 'System.Fabric.FabricException' in mscorlib.dll
Microsoft.AspNet.Hosting.Internal.HostingEngine: Information: Request finished in 0,2593ms 500
Microsoft.AspNet.Server.Kestrel: Error: An unhandled exception was thrown by the application.
System.Fabric.FabricException: Invalid partition key/ID '{0}'  for selector {1}
</code></pre>

<p>My stateless service is a SingletonPartition, so do I need a partition key here? And if yes, how do I get the key? The Service Fabric Explorer doesn't provide me with this information for my stateless service. Here is the <code>ServiceManifest.xml</code> of my stateless service:</p>

<p><strong>ServiceManifest.xml (MasterDataMService):</strong></p>

<pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;ServiceManifest Name="MasterDataMServicePkg"
                 Version="1.0.0"
                 xmlns="http://schemas.microsoft.com/2011/01/fabric"
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
  &lt;ServiceTypes&gt;
    &lt;!-- This is the name of your ServiceType. 
         This name must match the string used in RegisterServiceType call in Program.cs. --&gt;
    &lt;StatelessServiceType ServiceTypeName="MasterDataMServiceType" /&gt;
  &lt;/ServiceTypes&gt;

  &lt;!-- Code package is your service executable. --&gt;
  &lt;CodePackage Name="Code" Version="1.0.0"&gt;
    &lt;EntryPoint&gt;
      &lt;ExeHost&gt;
        &lt;Program&gt;MasterDataMService.exe&lt;/Program&gt;
      &lt;/ExeHost&gt;
    &lt;/EntryPoint&gt;
  &lt;/CodePackage&gt;

  &lt;!-- Config package is the contents of the Config directoy under PackageRoot that contains an 
       independently-updateable and versioned set of custom configuration settings for your service. --&gt;
  &lt;ConfigPackage Name="Config" Version="1.0.0" /&gt;

  &lt;Resources&gt;
    &lt;Endpoints&gt;
      &lt;!-- This endpoint is used by the communication listener to obtain the port on which to 
           listen. Please note that if your service is partitioned, this port is shared with 
           replicas of different partitions that are placed in your code. --&gt;
      &lt;Endpoint Name="ServiceEndpoint" Type="Input" Protocol="http" Port="80"/&gt;
    &lt;/Endpoints&gt;
  &lt;/Resources&gt;
&lt;/ServiceManifest&gt;
</code></pre>

<p>After that I decided to set up a service communication with OWIN:</p>

<p><strong>MasterDataMService.cs:</strong></p>

<pre class="lang-cs prettyprint-override"><code>internal sealed class MasterDataMService : StatelessService, IMasterDataMService
{
  [...]      

  protected override IEnumerable&lt;ServiceInstanceListener&gt; CreateServiceInstanceListeners()
  {
    return new[]
    {
      new ServiceInstanceListener(initParams =&gt; new OwinCommunicationListener("MasterDataMService", new StartUp(), initParams))
    };
  }
}
</code></pre>

<p>Now I can acess my microservice by using a <code>HttpClient</code> in my <code>DefaultController</code>:</p>

<pre class="lang-cs prettyprint-override"><code>var client = new HttpClient();
var request = "http://localhost:80/MasterDataMService/api/values/query";
var result = string.Empty;
HttpResponseMessage response = await client.GetAsync(request);
if (response.IsSuccessStatusCode)
{
  result = await response.Content.ReadAsStringAsync();
}
</code></pre>

<p>But thats not what I originally wanted. I don't want to specifiy the service endpoint in my request. Instead I would like to communicate with my stateless service over a <code>ServiceProxy</code>. How do I achieve that here? What did I wrong? And how can I solve this Health State error with my ASP .NET 5 application which is deployed into my service fabric cluster?</p>

<p>Thanks for your time.</p>

<p><strong>Edit:</strong></p>

<p><em>Extended stacktrace of invalid partition key exception:</em></p>

<pre><code>Exception thrown: 'System.Fabric.FabricException' in mscorlib.dll
Microsoft.AspNet.Hosting.Internal.HostingEngine: Information: Request finished in 1,35ms 500
Microsoft.AspNet.Server.WebListener.MessagePump: Error: ProcessRequestAsync
System.Fabric.FabricException: Invalid partition key/ID '{0}'  for selector {1} ---&gt; System.Runtime.InteropServices.COMException: exception of HRESULT: 0x80071BBF
   at System.Fabric.Interop.NativeClient.IFabricServiceManagementClient4.EndResolveServicePartition(IFabricAsyncOperationContext context)
   at System.Fabric.FabricClient.ServiceManagementClient.ResolveServicePartitionEndWrapper(IFabricAsyncOperationContext context)
   at System.Fabric.Interop.AsyncCallOutAdapter2`1.Finish(IFabricAsyncOperationContext context, Boolean expectedCompletedSynchronously)
   --- End of inner exception stack trace ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Services.Client.ServicePartitionResolver.&lt;ResolveAsyncHelper&gt;d__2a.MoveNext()
--- End of stack trace from the previous location where the exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Services.Communication.Client.CommunicationClientFactoryBase`1.&lt;GetClientAsync&gt;d__a.MoveNext()
</code></pre>

<p>Please give me feedback if you need more. (full stack trace is 82 lines long)</p>

<p><em>Invalid scheme exception stack trace:</em></p>

<pre><code>Exception thrown: 'System.ArgumentException' in mscorlib.dll
Microsoft.AspNet.Hosting.Internal.HostingEngine: Information: Request finished in 1,45ms 500
Microsoft.AspNet.Server.WebListener.MessagePump: Error: ProcessRequestAsync
System.ArgumentException: the provided uri scheme 'http' is invalid; expected 'net.tcp'.
Parametername: via
   at System.ServiceModel.Channels.TransportChannelFactory`1.ValidateScheme(Uri via)
   at System.ServiceModel.Channels.ConnectionOrientedTransportChannelFactory`1.OnCreateChannel(EndpointAddress address, Uri via)
   at System.ServiceModel.Channels.ChannelFactoryBase`1.InternalCreateChannel(EndpointAddress address, Uri via)
   at System.ServiceModel.Channels.ServiceChannelFactory.ServiceChannelFactoryOverDuplexSession.CreateInnerChannelBinder(EndpointAddress to, Uri via)
   at System.ServiceModel.Channels.ServiceChannelFactory.CreateServiceChannel(EndpointAddress address, Uri via)
   at System.ServiceModel.Channels.ServiceChannelFactory.CreateChannel(Type channelType, EndpointAddress address, Uri via)
   at System.ServiceModel.DuplexChannelFactory`1.CreateChannel(InstanceContext callbackInstance, EndpointAddress address, Uri via)
   at System.ServiceModel.DuplexChannelFactory`1.CreateChannel(InstanceContext callbackInstance, Binding binding, EndpointAddress endpointAddress)
   at Microsoft.ServiceFabric.Services.Communication.Wcf.Client.WcfCommunicationClientFactory`1.&lt;CreateClientAsync&gt;d__2.MoveNext()
--- End of stack trace from the previous location where the exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.ServiceFabric.Services.Communication.Client.CommunicationClientFactoryBase`1.&lt;CreateClientWithRetriesAsync&gt;d__1e.MoveNext()
</code></pre>