簡體   English   中英

REST WCF數據服務的簡單示例

[英]Simple example with REST WCF Data Service

我需要開發兩個站點之間的數據傳輸,並相信使用我們的.Net環境,RESTful實現將比使用FTP (ugh)更好。 但是,很難找到簡單的示例,並且REST基礎已被ADO.NET或許多巧妙的細節所遮蓋,因此我試圖使自己變得非常簡單。 盡管如此,我仍需要一些原則和實施方面的幫助才能使其正常工作。

在VisualStudio Web項目中,我創建了一個新項WCF Data Service和一個數據類。 這是App_Code \\ WidgetRecord.cs:

//using System;
using System.Collections.Generic;//List
using System.Linq;//Where
//using System.Web;
using System.ServiceModel;//ServiceContract, OperationContract
using System.Runtime.Serialization;//DataContract
using System.Diagnostics;//Debug.WriteLine()

/// <summary>
/// Declare operations for a service
/// </summary>
[ServiceContract]
public interface IScandataService
{
    [OperationContract]
    List<WidgetRecord> List();

    [OperationContract]
    WidgetRecord Get(string Id);

    [OperationContract]
    int Put(string Id, string Desc);
}//end interface

/// <summary>
/// Fake database storage for testing the WCF Data Service
/// </summary>
public static class Database
{
    /// <summary>
    /// Fake database table
    /// </summary>
    public static List<WidgetRecord> WidgetTable = new List<WidgetRecord>() { 
    new WidgetRecord("0001", "red"), 
    new WidgetRecord("0002", "blue") };
}

/// <summary>
/// Implement operations for a service.
/// Representation of a table of widgets identified by scanned barcodes
/// </summary>
[DataContract]
public class WidgetRecord : IScandataService
{
    /// <summary>
    /// Row column: the id which could be a scanned barcode
    /// </summary>
    public string Id { get; set; }

    /// <summary>
    /// Row column: widget description.
    /// (Other columns could be a timestamp, location etc)
    /// </summary>
    public string Desc { get; set; }

    /// <summary>
    /// Dummy initializer, needed for ....(??)
    /// </summary>
    public WidgetRecord()
    {
    return;
    }

    /// <summary>
    /// Initializer to populate the fake database storage.
    /// Creates a new widget record.
    /// </summary>
    /// <param name="Id"></param>
    public WidgetRecord(string Id, string Desc)
    {
    this.Id = Id;
    this.Desc = Desc;
    return;
    }

    /// <summary>
    /// List all stored widgets
    /// </summary>
    /// <returns></returns>
    [OperationContract]
    public List<WidgetRecord> List()
    {
    return Database.WidgetTable;
    }

    /// <summary>
    /// Get info on an existing widget
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    [OperationContract]
    public WidgetRecord Get(string Id)
    {
    WidgetRecord sd = Database.WidgetTable.Where(n => n.Id == Id).FirstOrDefault();
    if (sd == null)
        Debug.WriteLine(string.Format("Found: {0} - {1}", sd.Id, sd.Desc));
    else
        Debug.WriteLine(string.Format("Not found: id={0}", Id));
    return sd;
    }

    /// <summary>
    /// Add a new widget to the database
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="Desc"></param>
    /// <returns></returns>
    [OperationContract]
    public int Put(string Id, string Desc)
    {
    Database.WidgetTable.Add(new WidgetRecord(Id, Desc));
    Debug.WriteLine(string.Format("Put: {0} - {1}", Id, Desc));
    return 0;
    }
}//end class

在其他資源中,我經常看到帶有字段成員的[DataContract]partial class ,以及帶有方法的另一個類。 我不明白為什么要分開。 我只是想將ServiceContract接口用作數據類的基類。 無論如何,我的帶有字段和方法的類可以正常構建。

我在WcfDataService.svccode-behind引用了上述類,即App_Code\\WcfDataService.cs

//using System;
using System.Data.Services;//IDataServiceConfiguration, EntitySetRights, ServiceOperationRights, DataServiceProtocolVersion
//using System.Data.Services.Common;
//using System.Collections.Generic;
//using System.Linq;
//using System.ServiceModel.Web;

public class WcfDataService : DataService<WidgetRecord>
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(IDataServiceConfiguration config)
    {
    // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
    // Examples:
    config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
    //config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    return;
    }
}//end class

所有這些都可以構建和運行,但是基本上什么也沒做。

http://localhost:56794/website_for_rest/wcfDataService.svc/
-->
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<service xmlns="http://www.w3.org/2007/app" 
    xmlns:app="http://www.w3.org/2007/app" 
    xmlns:atom="http://www.w3.org/2005/Atom" 
    xml:base="http://localhost:56794/website_for_rest/WcfDataService.svc/">
    <workspace>
        <atom:title>Default</atom:title>
    </workspace>
</service>

我無法在URL中添加命令:

http://localhost:56794/website_for_rest/wcfDataService.svc/List
-->
page not found

我是否需要在web.config添加一些內容? VS給了我一個126行的web.config ,我不知道在哪里添加什么。

任何幫助表示贊賞。

答案(至少對我而言)是,最簡單的REST示例不使用WCF數據服務,后者是簡化REST的框架。 但是,如果您有大量數據和要執行的許多操作,則僅需要簡化REST。 首先,為了進行簡單的數據傳輸,您可以在沒有框架的情況下進行REST。 而當您需要一個框架時,有很多選擇,例如,請參閱此幾十個框架的列表 首先,SOAP是較老的一種,並且由於過於復雜而失寵。 與Web服務相同。 顯然,WCF數據服務(意在繼承WS)將被Web API取代。

這種框架的問題在於它們可能會產生新的問題。 對我來說,必須升級我的工具是一個缺點,因為帶有.Net3.5的VS2010不支持Web API。 升級是一件好事,但是如果它干擾了我正在從事的大型項目,那不是一件好事。 還是WCF數據服務對我來說還不清楚,它具有我不掌握的各種智能綁定,請參閱我的問題。 WCF DS存在許多示例,但已與ADO.NET結合使用,以幫助您處理大量表。

與Microsoft環境(VS,.Net,Asp)保持一致,從純REST開始很容易。 只需創建一個空網頁,例如Default.aspx ,然后在其Page_Load()開始編寫REST功能。

要查看GET,PUT,POST等請求是否已到達,請查看Request.RequestType

要獲取HTTP正文中的數據: Request.BinaryRead(Request.ContentLength)

如果您需要處理授權,請從Authentication Http標頭行中獲取用戶名和密碼,並帶有: Request.Params["HTTP_AUTHORIZATION"] ,它是base64編碼的。 然后,您將需要與HTTPS進行安全連接,以在傳輸(TCP)級別對整個HTTP數據包(包括HTTP標頭)進行加密。

要返回HTTP狀態代碼和/或錯誤消息,只需在頁面上添加常規的asp文本控件即可。 如果要RESTful返回數據結構,也可以用Response對象來替換整個http響應。

使用Telerik fiddler工具,可以很容易地制作一個HTTP數據包來測試您的簡單REST服務器頁面。

為了使客戶可以使用更好的URL訪問您的頁面,您需要使用一些URL重寫。 這涉及下載和安裝重寫模塊,以及向您的web.config添加規則。 通過詳細的解釋和示例,這似乎是一個很好的來源。

當然,使用一個好的框架會很好,但是准系統的實現是研究REST的一種好方法,並且已經比舊的FTP交換數據的方法有了很大的改進,這在我的行業中仍然很常見。

感謝Mason,他幫助我意識到WCF DS只是眾多框架之一。

暫無
暫無

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

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