c# - 从 Windows PHONE 8.1 调用时 WCF 服务不公开方法

标签 c# wcf windows-phone-8.1

因为我使用的是 Windows Phone 8.1,所以我无法像以前的应用程序那样调用我的 WCF 服务。

经过一些搜索,我找到了以下从 window phone 8.1 调用服务的替代方法

try
{
    string responseBodyAsText;

    HttpResponseMessage res = await httpClient.GetAsync("http://localhost:50436/FabSvc.svc");
    res.EnsureSuccessStatusCode();

    string status = res.StatusCode + " " + res.ReasonPhrase + Environment.NewLine;
    responseBodyAsText = await res.Content.ReadAsStringAsync();
    responseBodyAsText = responseBodyAsText.Replace("<br>", Environment.NewLine); // Insert new lines
    string output = responseBodyAsText;
}
catch (HttpRequestException hre)
{
    string status = hre.ToString();
}
catch (Exception ex)
{
    // For debugging
    string status = ex.ToString();
}

此代码返回 OK 状态代码(见下文)以及一些基本数据。但我的问题是我不知道如何从这一点访问任何方法。我做错了什么?

enter image description here

编辑:当前 WCF 服务(简化)

service.svc

namespace ServiceName.WCF
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class FabSvc : ICollection, ICompositionType
{
    /// <summary>
    /// Pings this instance.
    /// </summary>
    /// <returns></returns>
    public bool Ping()
    {
        return true;
    }

    /// <summary>
    /// Gets all CompositionTypes.
    /// </summary>
    /// <returns></returns>
    public List<CompositionTypeBase> GetAllCompositionTypes()
    {
        List<CompositionTypeBase> allCompositionTypes = new List<CompositionTypeBase>();
        try
        {
            allCompositionTypes = CompositionTypeBase.GetAllCompositionTypes();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return allCompositionTypes;
    }
}

Icollection.cs

namespace ServiceName.WCF
{
    [ServiceContract]
    interface ICollection
    {
        [OperationContract]
        List<CollectionBase> GetAllCollections();
    }
}

CollectionBase.cs

namespace ServiceName.WCF.Entities
{
    public class CollectionBase
    {
        public int CollectionID { get; set; }

        public string Description { get; set; }

        /// <summary>
        /// Gets all seasons.
        /// </summary>
        /// <returns></returns>
        public static List<CollectionBase> GetAllCollections()
        {
            List<CollectionBase> allCollections = new List<CollectionBase>();
            IEnumerable<Collection> collections = Collection.GetAll();
            foreach (var collection in collections)
            {
                CollectionBase seasonBase = new CollectionBase();
                seasonBase.CollectionID = collection.CollectionID;
                seasonBase.Description = collection.Description;
                allCollections.Add(seasonBase);
            }
            return allCollections;
        }
    }
}

Web.config

        <configuration>
      <configSections>
        <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" />
        <add key="ImageFilePath" value="C:\websites\images\"/>
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" maxRequestLength="20000000" />
      </system.web>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior>
              <serviceMetadata httpGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="true" />
              <serviceThrottling maxConcurrentCalls="50" />
              <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <protocolMapping>
          <add binding="basicHttpBinding" scheme="http" />
        </protocolMapping>
        <bindings>
          <basicHttpBinding>
            <binding maxBufferPoolSize="20000000" maxReceivedMessageSize="20000000" maxBufferSize="20000000" openTimeout="12:00:00" receiveTimeout="12:00:00" sendTimeout="12:00:00" closeTimeout="12:00:00">
              <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
            </binding>
          </basicHttpBinding>
        </bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0" />
      </system.serviceModel>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
        <directoryBrowse enabled="true" />
      </system.webServer>
      <connectionStrings>
        <add name="ServiceNameEntities" connectionString="CONNECTION_STRING_INFO" 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>

最佳答案

当您使用 HttpClient 时,您打算将数据发布到端点,因此这里没有契约。

您在创建代理时通过添加引用或使用 wcfutil“看到”操作。

对于 RestFul 服务,您可以像这样简单地调用操作:

HttpResponseMessage res = await httpClient.GetAsync("http://localhost:50436/FabSvc.svc/GetAllCollections/value");

但是您的服务需要 SOAP 请求,因此您需要使用 SOAP/XML 发出请求才能使用您的方法。 在 SOAP 信封内,您通知服务您要执行的操作,如下所示:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <OperationName xmlns="http://tempuri.org/">

您还可以将操作包含在标题中。 在下面的示例中,我使用了 WebClient:

using (var client = new WebClient())
{
    var data = GetSoap();
    client.Headers.Add("Content-Type", "text/xml;charset=utf-8");
    client.Headers.Add("SOAPAction", "\"http://tempuri.org/ICollection/GetAllCollections\"");
    var response = client.UploadString("http://localhost:50436/FabSvc.svc", data);
    Console.WriteLine(response);
}

希望对你有帮助

关于c# - 从 Windows PHONE 8.1 调用时 WCF 服务不公开方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32627316/

相关文章:

asp.net - 如何 ping 诸如 svc、asmx 之类的 Web 服务

.net - 如何使用统一 IoC 容器

wcf - 使用 makecert.exe 创建的证书在哪里?

azure - 将视频从 Windows Phone 8 上传到 Azure 存储

c# - WP8.1 应用程序在导航到另一个页面时崩溃

c# - 检查手机上的互联网连接

c# - 如何将应用程序的构建日期放在应用程序的某处?

c# - 为什么我的 C# 代码比我的 C 代码快?

c# - 如何在 Property.Settings.Default 中存储图像?

c# - 在 C# 中从 Base64 解码