簡體   English   中英

Xamarin表單的Rest + WCF集成

[英]Rest + WCF Integration for Xamarin Forms

我正在做一個Xamarin Forms項目,該項目需要連接到WCF服務。 我必須使用Rest來訪問它,因此我選擇使用PCL兼容的RestSharp版本。 我已經完成了許多基於SOAP的Web服務,但這是我第一次深入研究Rest,感覺好像缺少了一些非常基本的東西。 我已經確認在進行SOAP調用時我的Web服務可以正常運行,因此我認為我設置不正確。

這是我的Web服務的示例代碼:

Imports System.IO
Imports System.Net
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web

<ServiceContract()>
Public Interface Iapi
    <WebInvoke(Method:="PUT",
           UriTemplate:="Login/Email/{Email}/Password/{Password}",
           RequestFormat:=WebMessageFormat.Json,
           ResponseFormat:=WebMessageFormat.Json)>
    <OperationContract(AsyncPattern:=True)>
    Function Login(email As String, password As String) As String
End Interface

這是我嘗試調用該服務的示例代碼:

public void Login(string email, string password)
    {
        RestClient client = new RestClient("http://www.example.com/service.svc/");
        RestRequest request = new RestRequest
        {
            Method = Method.PUT,
            Resource = "Login/Email/{Email}/Password/{Password}",            
            RequestFormat = DataFormat.Json
        };

        request.AddParameter("Email", email, ParameterType.UrlSegment);
        request.AddParameter("Password", password,ParameterType.UrlSegment);

        client.ExecuteAsync(request, response => {
            session = response.Content;
            ActionCompleted(this, new System.EventArgs());
        });            
    }

當我在上面進行調用時,沒有異常,只有空字符串返回值。 在瀏覽器中也會發生同樣的事情。 我懷疑我的服務定義。 我有一些可能有點基本的問題,但希望將來對其他WCF / Rest初學者有所幫助。

1.服務定義中的UriTemplate有什么問題(如果有的話)? 適當的UriTemplate會是什么樣?

2.我應該對這種服務調用使用PUT方法,還是更合適使用GET或POST?

3.我的Web服務定義中顯然還有其他地方嗎?

4.將完整服務uri( http://www.example.com/service.svc/ )傳遞給Rest客戶端是否正確?

5.對於Rest初學者,還有關於WCF-Rest組合的其他建議嗎?

  1. 如果您使用的是GET,則正確的URI模板可能看起來像這樣:

C#

[OperationContract]
[WebGet(UriTemplate  = "Book/{id}")]
Book GetBookById(string id);

VB:

<OperationContract()> _ 
<WebGet(UriTemplate:="Book/{id}")> _ 
Function GetBookById(ByVal id As String) As Book

然后,您可以使用http://example.com/Book/1為ID == 1的圖書進行調用。

  1. 在Microsoft世界中,PUT通常用於創建或更新數據,例如新任務,訂單等。但是,即使我個人認為POST或GET是更准確的方法,也可以將其用於登錄。 但這只是我的觀點。

有關更多信息,請參見此問題: REST中的PUT與POST

  1. 您的聲明中似乎沒有什么缺失。

  2. 如果您無法通過瀏覽器訪問它,那可能不是RestSharp的用法錯誤。 但是,這里有一些注意事項。 使用異步方法時,您通常會想嘗試使用.NET的async / await-pattern。 然后,該請求不會鎖定主線程。

范例: http//www.dosomethinghere.com/2014/08/23/vb-net-simpler-async-await-example/

這是我在Xamarin項目中用於調用服務的一小段代碼:

protected static async Task<T> ExecuteRequestAsync<T>(string resource,
    HttpMethod method,
    object body = null,
    IEnumerable<Parameter> parameters = null) where T : new()
{
    var client = new RestClient("http://example.com/rest/service.svc/");
    var req = new RestRequest(resource, method);
    AddRequestKeys(req);

    if (body != null)
        req.AddBody(body);

    if (parameters != null)
    {
        foreach (var p in parameters)
        {
            req.AddParameter(p);
        }
    }

    Func<Task<T>> result = async () =>
    {
        var response = await client.Execute<T>(req);
        if (response.StatusCode == HttpStatusCode.Unauthorized)
            throw new Exception(response.Data.ToString());
        if (response.StatusCode != HttpStatusCode.OK)
            throw new Exception("Error");

        return response.Data;
    };

    return await result();
}
  1. 對,那是正確的。

  2. 您如何托管WCF? 如果使用IIS,您的web.config是什么樣的? 這是一個例子:

作為附帶說明,我注意到您提到您需要訪問WCF服務。 您是否考慮過改用.NET Web API? 它為創建RESTful端點提供了更簡單的方法,而無需進行配置。 它的實現和使用更簡單,但是它沒有提供與WCF服務相同的靈活性。

為了調試WCF服務,我強烈建議您使用“ WCF測試客戶端”: https : //msdn.microsoft.com/zh-cn/library/bb552364(v=vs.110).aspx

在哪里可以找到WcfTestClient.exe(Visual Studio的一部分)

在web.config中啟用了元數據后,您將能夠看到所有可用的方法。 示例配置如下:

<configuration>
  <system.serviceModel>
    <services>
      <service name="Metadata.Example.SimpleService">
        <endpoint address=""
                  binding="basicHttpBinding"
                  contract="Metadata.Example.ISimpleService" />
      </service>
    </services>
    <behaviors>

    </behaviors>
  </system.serviceModel>
</configuration>

來源: https : //msdn.microsoft.com/en-us/library/ms734765(v=vs.110).aspx

如果沒有幫助,您是否還可以提供web.config和服務實現?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM