无法从Android将数据发布到WCF

时间:2014-01-18 11:31:16

标签: c# android asp.net wcf web-services

我正在尝试从Android应用程序向WCF服务发送数据,但不知何故该服务似乎没有通过android调用。我通过 LOGCAT 中的adnroid收到 STATUSCODE 值= 500(这意味着内部服务器错误)我通过源代码100次,但没有弄清楚Bug。几乎检查了与我的问题相关的所有帖子,但仍然没有得到任何解决方案。

这是代码

Android代码:

private class sendPostData extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub

    HttpPost request = new HttpPost( LOGIN_SERVICE_URL + "/MyCar");
    request.setHeader("Accept", "application/json");            
    request.setHeader("Content-type", "application/json");
    JSONStringer getCarInfo;
    try {
        getCarInfo = new JSONStringer()
            .object()
                .key("myCar")
                    .object()
                        .key("Name").value(edt_carName.getText().toString())                                  
                        .key("Make").value(edt_carMake.getText().toString())
                        .key("Model").value(edt_carModel.getText().toString())
                    .endObject()
                .endObject();

    StringEntity entity = new StringEntity(getCarInfo.toString());

    request.setEntity(entity);

    // Send request to WCF service
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
    Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());
    }
    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(String result) {
    txt_verif.setText("Success");
}
}

除了调用WCF服务之外,一切都在android代码中正常工作。我多次调试代码并收到statuscode = 500

HERE是WCF服务

Service.cs

public class Service1 : IService1
{
    public void UpdateMyCar(myCar myCar) {

        string strConnectionString = ConfigurationManager.ConnectionStrings["Database1"].ConnectionString;
        SqlConnection conn = new SqlConnection(strConnectionString);
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("Insert into TestingTable (Name,Make,Model) Values (@Name,@Make,@Model)", conn)) {

            cmd.Parameters.AddWithValue("@Name", myCar.Name);
            cmd.Parameters.AddWithValue("@Make", myCar.Make);
            cmd.Parameters.AddWithValue("@Model", myCar.Model);

            int queryResult = cmd.ExecuteNonQuery();
        } conn.Close();
    }

logcat的

WebInvoke     Saving : 500

IService1.svc

[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "MyCar",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    void UpdateMyCar(myCar myCar);
}

[DataContract]
public class myCar 
{

    [DataMember(Name="Name")]
    public string Name 
    { 
        get; 
       set; 
    }

    [DataMember(Name="Model")]
    public string Model 
    { 
        get; 
        set; 
    }

    [DataMember(Name="Make")]
    public string Make 
    { 
        get;
        set; 
    }

的Web.Config

<?xml version="1.0"?>

<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
    <compilation debug="true" targetFramework="4.0">
    </compilation>

    <authentication mode="Windows"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
<system.serviceModel>
    <services>
        <service name="CarSercive.Service1" behaviorConfiguration="CarSercive.Service1Behavior">
            <!-- Service Endpoints -->
            <endpoint address="" binding="webHttpBinding" contract="CarSercive.IService1">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="CarSercive.Service1Behavior">
                <serviceMetadata httpGetEnabled="true"/>

                <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

此服务也在IIS上发布。我还使用谷歌浏览器扩展 SIMPLE REST CLIENT 检查了该服务并收到了内部服务器错误

4 个答案:

答案 0 :(得分:0)

问题是您的主机名与手机中的主机名不匹配。

您可以关闭地址过滤器以暂时解决此问题:

[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]
public class Service1 : IService1
{
    ....
}

但是你应该在发布到生产时修复主机名

答案 1 :(得分:0)

使用正确的端口号在您的计算机中创建一个域,并确保您可以使用Google的Rest客户端来调用该服务。如果它有效,那么如果您使用Android手机拨打相同的电话,则不会发现任何问题

以下文章将帮助您设置具有正确端口号的虚拟目录。[http://www.hosting.com/support/iis7/create-new-sites-in-iis-7/]

注意您不能直接从您的mobile.atleast调用localhost尝试使用ipaddress调用该服务。[http:// localhost / service / mycar] =&gt; [http:// DemoService /服务/ mycar]

答案 2 :(得分:0)

以下代码将帮助您深入调试代码。

catch (Exception ex)
            {
                WebException webexception = (WebException)ex;
                var responseresult = webexception.Response as HttpWebResponse;

                //Code to debug Http Response
                var responseStream = webexception.Response.GetResponseStream();
                string fault_message = string.Empty;
                int lastNum = 0;
                do
                {
                    lastNum = responseStream.ReadByte();
                    fault_message += (char)lastNum;
                } while (lastNum != -1);
                responseStream.Close();
}

答案 3 :(得分:0)

没关系,我在 web.config 文件中进行了一些更改并获得了解决方案。我的案例中还缺少<endpointBehaviors> 标记以及其他一些内容。这是 web.config 文件的更新代码。

[更新的web.config文件]

<?xml version="1.0"?>
<configuration>
<appSettings/>
  <connectionStrings>
<add name="DB" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Munyb\Documents\Visual Studio 2010\Projects\CarSercive\CarSercive\App_Data\Database1.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
<system.web>
    <compilation debug="true" targetFramework="4.0">
    </compilation>
    <authentication mode="Windows"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/></system.web>
<system.serviceModel>
    <services>
        <service name="CarSercive.Service1" behaviorConfiguration="RESTfulServ">
            <!-- Service Endpoints -->
    <endpoint address="" binding="webHttpBinding" contract="CarSercive.IService1" behaviorConfiguration="web"></endpoint>
        </service>
    </services>
    <behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="RESTfulServ">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
        </serviceBehaviors>

    </behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
</system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"> 
    </modules>
  </system.webServer>
</configuration>