假設您想公開一個名爲Person的實體。 WCF REST服務可能如下所示:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public partial class PeopleWebService
{
[WebGet(UriTemplate = "")]
public List<Person> GetCollection()
{
try
{
IPeopleRepository repository = ServiceLocator.GetInstance<IPeopleRepository>();
var people = repository.GetPeople();
// use automapper to map entities to Person resource
var result = Mapper.Map<List<Person>>(people);
return result;
}
catch (Exception exception)
{
// do logging etc
throw new WebFaultException(HttpStatusCode.InternalError);
}
}
/* other methods */
}
這些服務也可以由T4生成。
請注意,WCF服務本身不需要接口。我通常不直接在WCF服務中公開任何數據庫實體,因爲我的服務發展不同於我的數據庫實體。一旦API發佈,它應該幾乎保持不變。這可以防止我改變我的數據庫模式以適應新的需求。
相反,我將我的實體映射到資源。所以Person
5如下所示:
[DataContract]
public class Person
{
[DataMember]
public string GivenName { get; set; }
/* more properties */
}
這可能是使用T4來生成這些以及一件好事。路由定義是這樣的:
public void Register(RouteCollection routes)
{
routes.AddService<WorkspaceWebService>("api/v1/people");
}
要從ASP.NET MVC項目中使用它,你可以分享如上定義組件的資源(又名人),或者你可以使用T4來生成一個獨立的一組資源幾乎相同,但具有ASP.NET MVC所需的一些附加屬性,如用於驗證的屬性。我會生成它,因爲我的ASP.NET MVC視圖模型通常獨立於我的REST資源發展。
讓我們假設您的REST服務運行在https://api.example.com/,您的MVC網站運行在https://www.example.com/。您的PeopleController可能如下所示。
public class PeopleController : ControllerBase
{
[HttpGet]
public ActionResult Index()
{
return View(Get<List<Person>>(new Uri("https://api.example.com/api/v1/people")));
}
protected T Get<T>(Uri uri)
{
var request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "GET";
request.ContentType = "text/xml";
using (var response = (HttpWebResponse) request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
Debug.Assert(responseStream != null, "responseStream != null");
var serializer = new DataContractSerializer(typeof (T));
return (T) serializer.ReadObject(responseStream);
}
}
}
}
從你的問題,我假設你想使用JSON。爲此,您只需在請求上設置適當的ContentType並使用DataContractJsonSerializer而不是DataContractSeralizer。請注意,日期和DataContractJsonSerializer存在一些問題。如果contenttype是「text/xml」,WCF rest服務將自動返回XML,如果是「application/json」,則WSS rest服務將自動返回JSON。
請注意,MVC應用程序不知道數據庫,數據庫實體或其數據庫上下文。事實上,MVC應用程序中沒有數據庫邏輯。您將必須密切關注安全性,因爲WCF休息服務中缺少用戶上下文。但是,這是一個完全不同的討論。
這驗證了我上週發現的內容,因爲這可能不是最好的方法。在使用WCF RESTful模板時,您不得不爲數據序列化添加額外的代碼,即使它是純粹的.Net應用程序。我後來意識到,我從來不想直接從客戶端(以任何方式)訪問DAL。但是未來的項目可能需要這種靈活性序列化過程的很好解釋。謝謝。 – ElHaix 2012-03-26 15:08:59
您可以使用WCF自動完成所有序列化等[在本例中列出](http://blogs.msdn.com/b/pedram/archive/2008/04/21/how-to-consume-rest-服務與 - wcf.aspx)。但是,您在客戶端上放鬆了很多功能,特別是在處理錯誤時。 – bloudraak 2012-03-26 18:18:37