c# - 无法从 android 中使用 WCF 方法

标签 c# android wcf

这是我第一次使用 WCF 和 Android。所以,很抱歉问了一个简单的问题 :)
这是来自 wcf 服务库:

[ServiceBehavior]
    public class CheckInService : ICheckInService
    {
        public string Hello()
        {
            return "Message from WCF!";
        }
    }
    [ServiceContract]
    public interface ICheckInService
    {
        [OperationContract]
        [WebInvoke(
            Method = "POST",
            UriTemplate = "Hello",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        string Hello();
    }

这是来自wcf服务网站Service.svc

<%@ ServiceHost Language="C#" Debug="true" Service="TYT.Service.CheckInService"  %>

这是来自 wcf 服务库项目的 app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <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>
    <services>
      <service name="TYT.Service.CheckInService">
        <endpoint address="publicService" binding="basicHttpBinding" contract="TYT.Service.ICheckInService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/TYT.Service/Service1/" />
          </baseAddresses>
        </host>
      </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="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

这是来自 wcf 服务网站的 web 配置:

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="TYT.Service.CheckInService">
        <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
          contract="TYT.Service.ICheckInService" />
      </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="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>


安卓代码

private final static String SERVICE_URI = "http://10.0.2.2/tytservice/Service.svc";    
try {



            // Send GET request to <service>/GetPlates
            HttpGet request = new HttpGet(SERVICE_URI + "/Hello");
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);

            HttpEntity responseEntity = response.getEntity();

            // Read response data into buffer
            char[] buffer = new char[(int)responseEntity.getContentLength()];
            InputStream stream = responseEntity.getContent();
            InputStreamReader reader = new InputStreamReader(stream);
            reader.read(buffer);
            stream.close();

            String data = new String(buffer);

但在数据字符串中,我得到的是整个 HTML 文档,但有以下错误:

<span><H1>Server Error in '/tytservice' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>The resource cannot be found.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. &nbsp;Please review the following URL and make sure that it is spelled correctly.
            <br><br>

            <b> Requested URL: </b>/tytservice/Service.svc/Hello<br><br>
...
</html>
<!-- 
[EndpointNotFoundException]: There was no channel actively listening at &#39;http://vlada-nb/tytservice/Service.svc/Hello&#39;. This is often caused by an incorrect address URI. Ensure that the address to which the message is sent matches an address on which a service is listening.
   at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
[HttpException]: There was no channel actively listening at &#39;http://vlada-nb/tytservice/Service.svc/Hello&#39;. This is often caused by an incorrect address URI. Ensure that the address to which the message is sent matches an address on which a service is listening.
   at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
   at System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar)
-->

当我在浏览器中导航到 http://localhost/tytservice/Service.svc 时,我得到了服务描述,但是如果我添加 http://localhost/tytservice/Service.svc/你好我又收到404了。
看起来这个方法没有公开,但我不知道我在这里错过了什么?

最佳答案

问题出在这里:

WebInvoke(
    Method = "POST",

您正在使用 HTTP GET 而不是 POST 调用方法:

HttpGet request = new HttpGet(SERVICE_URI + "/Hello");
request.setHeader("Accept", "application/json");
// ...

您可以通过将方法更改为 Method = "GET" 或使用 HttpPost 来解决此问题调用它。

另请查看此相关问题:

关于c# - 无法从 android 中使用 WCF 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11064066/

相关文章:

android - Android 应用程序中的 QR 码游戏

c# - WCF 4.0 SOA 提交作为事务

c# - 如何在用户未登录的情况下保护授权网站?

c# - 用于验证 double 值的正则表达式

java - 当我启动 Intent ACTION_OPEN_DOCUMENT_TREE 时,它会自动打开空的最近文件夹吗?

c# - XAMARIN (C#) - 有没有办法以编程方式为 TextView 添加下划线?

wcf - WcfConfigValidationEnabled 有什么作用?

wcf - POST/PUT静态服务的URI模板

c# - 从 C# 代码以波斯语发布时,在 mysql 数据库中插入 "????"

c# - 处理我的 ObjectContext 的正确方法是什么?