在Xamarin跨平台应用程序中使用WCF服务

本文关键字:WCF 服务 Xamarin 跨平台 应用程序 | 更新日期: 2023-09-27 18:21:26

我创建了一个WCF服务,它从SQL数据库中检索数据,并可以将数据更新和修改到SQL数据库中。我正在尝试从xamarin为android和xamarin的iOS调用WCF方法。我搜索了很多关于如何通过xamarin for android和xamarin in for iOS从WCF服务调用PUT和POST方法的示例,但没有成功。我在下面添加了WCF代码以供参考。。。甚至创建了Web API,但所有使用Web API的示例和教程都是关于如何调用GET方法的。我没有看到任何参考文档显示如何从WCF或Web api跨平台调用PUT或Post方法。我已经通过Fiddler测试了WCF服务,并且运行良好。下一步该怎么办。。我已经使用xamarin文档中提到的SlsvcUtil.exe为该web服务创建了代理。有人能发布一个xamarin的例子吗。将从下面的wcf服务调用Update或delete方法的Android。绝望地寻求帮助。服务包含webHttp绑定。

WCF-

Service1.svc.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Web; 
using System.Text;
public class Service1 : IService1 
{ 
    public List GetDeptsList() 
    { 
        using (DeptDBEntities entities = new DeptDBEntities()) 
        { 
            return entities.Depts.ToList(); 
        } 
    }
    public Dept GetDeptByID(string no)
    {
        try
        {
            int deptId = Convert.ToInt32(no);
            using (DeptDBEntities entities = new DeptDBEntities())
            {
                return entities.Depts.SingleOrDefault(dept => dept.no == deptId);
            }
        }
        catch
        {
            throw new FaultException("Something went wrong");
        }
    }
    public void AddDept(string name)
    {
        using (DeptDBEntities entities = new DeptDBEntities())
        {
            Dept dept = new Dept { name = name };
            entities.Depts.Add(dept);
            entities.SaveChanges();
        }
    }
    public void UpdateDept(string no, string name)
    {
        try
        {
            int deptId = Convert.ToInt32(no);
            using (DeptDBEntities entities = new DeptDBEntities())
            {
                Dept dept = entities.Depts.SingleOrDefault(b => b.no == deptId);
                dept.name = name;
                entities.SaveChanges();
            }
        }
        catch(Exception e)
        {
            throw new FaultException(e.Message);
        }
    }
    public void DeleteDept(string no)
    {
        try
        {
            int deptId = Convert.ToInt32(no);
            using (DeptAppDBEntities entities = new DeptAppDBEntities())
            {
                Dept dept = entities.Depts.SingleOrDefault(b => b.no == deptId);
                entities.Depts.Remove(dept);
                entities.SaveChanges();
            }
        }
        catch
        {
            throw new FaultException("Something went wrong");
        }
    }
}

web.config

   <?xml version="1.0"?>
      <configuration>
      <configSections>
       <section name="entityFramework"   type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
     </configSections>
     <system.web>
     <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
      </assemblies>
      </compilation>
      <pages controlRenderingCompatibilityVersion="4.0"/>
      </system.web>
      <system.serviceModel>
                 <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      </behaviors>
      <services>
      <service name="WcfWithJsonP.Service1" behaviorConfiguration="restfulBehavior">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="" contract="WcfWithJsonP.IService1"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost/Service1"/>
          </baseAddresses>
        </host>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
       </services>
      <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp defaultOutgoingResponseFormat="Json"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="restfulBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      </behaviors>
      <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
      </system.serviceModel>
     <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
        <directoryBrowse enabled="true"/>
     </system.webServer>
     <entityFramework>
     <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,   EntityFramework">
      <parameters>
        <parameter value="v12.0"/>
      </parameters>
     </defaultConnectionFactory>
     </entityFramework>
    </configuration

>

的Main.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:minWidth="25px"
    android:minHeight="25px">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="134.1dp"
        android:layout_height="fill_parent"
        android:minWidth="25px"
        android:minHeight="25px">
        <TextView
            android:text="Enter No:"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:layout_width="163.4dp"
            android:layout_height="wrap_content"
            android:id="@+id/No"
            android:layout_marginBottom="27.5dp"
            android:layout_marginTop="0.0dp"
            android:layout_marginLeft="5dp" />
        <TextView
            android:text="Enter name:"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:layout_width="252.7dp"
            android:layout_height="wrap_content"
            android:id="@+id/Name"
            android:layout_marginBottom="27.5dp"
            android:layout_marginTop="0.0dp"
            android:layout_marginLeft="5dp"
            android:enabled="false"
            android:visibility="invisible" />
    </LinearLayout>
    <Button
        android:id="@+id/Get"
        android:layout_width="fill_parent"
        android:layout_height="36.6dp"
        android:text="Get" />
    <Button
        android:id="@+id/ADD"
        android:layout_width="fill_parent"
        android:layout_height="36.6dp"
        android:text="ADD" />
    <Button
        android:id="@+id/Update"
        android:layout_width="fill_parent"
        android:layout_height="36.6dp"
        android:text="Update" />
    <Button
        android:id="@+id/Delete"
        android:layout_width="fill_parent"
        android:layout_height="36.6dp"
        android:text="Delete" />
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ValueNo"
        android:layout_marginBottom="27.5dp"
        android:layout_marginTop="0.0dp"
        android:background="@android:color/holo_purple" />
    <TextView
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/ValueName"
        android:layout_marginBottom="27.5dp"
        android:layout_marginTop="0.0dp"
        android:background="@android:color/holo_purple" />
</LinearLayout>

在Xamarin跨平台应用程序中使用WCF服务

这里有一个简单的代码片段作为指南:

//first at the class level, create a private variable for the client.
private Service1Client _client;
private Button _addButon;
private TextView _txtDeptName;
//Initialize the _client in the OnCreate() method.
protected override void OnCreate(Bundle bundle)
{
     base.OnCreate(bundle);
     var endpoint = new EndpointAddress("http://<ipAddress:port>/Service1.svc");
     var binding = new BasicHttpBinding{
        Name = "basicHttpBinding",
        MaxBufferSize = 2147483647,
        MaxReceivedMessageSize = 2147483647
    };
    TimeSpan timeout = new TimeSpan(0, 0, 30);
    binding.SendTimeout = timeout;
    binding.OpenTimeout = timeout;
    binding.ReceiveTimeout = timeout;
    _client = new Service1Client(binding, endpoint);
    _client.AddDeptCompleted += ClientAddDeptCompleted;
    _addButton = FindViewById<Button>(Android.Resources.Id.Add);
    _addbutton.Click += AddButton_Clicked;
    _txtDeptName = FindViewbyId<TextView>(Android.Resources.Id.Name);
}
//Then within the event handlers, do something like this
public void AddButton_Clicked(object sender, EventArgs e)
{
     _client.AddDeptAsync(_txtDeptName.Text);
}
//Handle the request completed event.
private void ClientAddDeptCompleted(object sender, AddDeptCompletedEventArgs addDeptCompletedEventArgs)
{
     //TODO: Something with the notification that the request has completed.
}

对于其他按钮和服务调用,您应该能够遵循类似的模式。如果我错别字了,我深表歉意。我从Xamarin网站上的一些内存和WCF说明开始。

首先必须将服务添加到项目中您可以使用以下命令执行此操作:

Cd C:''Program Files(x86)''Microsoft SDK '' Silverlight ''v5.0''Tools''SlSvcUtil.exehttp://localhost:2323/HisDashboardService/ProfilerService.svc/directory:"C:''Folder"

然后添加到创建的项目文件要使用添加的服务,必须遵循以下程序

public class ServiceAccessor
{
    static string serviceUrl = "http://172.16.12.17:7698/HisDashboardService/";
    public static readonly EndpointAddress ProfilerServiceEndPoint = new EndpointAddress(serviceUrl + "ProfilerService.svc");
    private ProfilerServiceClient _profilerServiceClient;
    private static ServiceAccessor _instanceServiceAccessor;
    public static ServiceAccessor Instance
    {
        get { return _instanceServiceAccessor ?? (_instanceServiceAccessor = new ServiceAccessor()); }
    }
    ServiceAccessor()
    {
        InitializeServiceClient();
    }
    private void InitializeServiceClient()
    {
        BasicHttpBinding binding = CreateBasicHttp();
        #region ProfilerService
        _profilerServiceClient = new ProfilerServiceClient(binding, ProfilerServiceEndPoint);
        #endregion ProfilerService
    }
    private static BasicHttpBinding CreateBasicHttp()
    {
        BasicHttpBinding binding = new BasicHttpBinding
        {
            Name = "basicHttpBinding",
            MaxBufferSize = 2147483647,
            MaxReceivedMessageSize = 2147483647
        };
        TimeSpan timeout = new TimeSpan(1, 0, 0);
        binding.SendTimeout = timeout;
        binding.OpenTimeout = timeout;
        binding.ReceiveTimeout = timeout;
        return binding;
    }
}