WCF Resful Service
[ServiceContract]
public interface IBookService
{
[OperationContract]
[WebGet]
List<Book> GetBooksList();
[OperationContract]
[WebGet(UriTemplate = "Book/{id}")]
Book GetBookById(string id);
[OperationContract]
[WebInvoke(UriTemplate = "AddBook/{name}")]
void AddBook(string name);
[OperationContract]
[WebInvoke(UriTemplate = "UpdateBook/{id}/{name}")]
void UpdateBook(string id, string name);
[OperationContract]
[WebInvoke(UriTemplate = "DeleteBook/{id}")]
void DeleteBook(string id);
}
實施服務
現在,服務實現部分將使用實體框架生成的上下文和實體來執行所有相應的操作。
public class BookService : IBookService
{
public List<Book> GetBooksList()
{
using (SampleDbEntities entities = new SampleDbEntities())
{
return entities.Books.ToList();
}
}
public Book GetBookById(string id)
{
try
{
int bookId = Convert.ToInt32(id);
using (SampleDbEntities entities = new SampleDbEntities())
{
return entities.Books.SingleOrDefault(book => book.ID == bookId);
}
}
catch
{
throw new FaultException("Something went wrong");
}
}
public void AddBook(string name)
{
using (SampleDbEntities entities = new SampleDbEntities())
{
Book book = new Book { BookName = name };
entities.Books.AddObject(book);
entities.SaveChanges();
}
}
public void UpdateBook(string id, string name)
{
try
{
int bookId = Convert.ToInt32(id);
using (SampleDbEntities entities = new SampleDbEntities())
{
Book book = entities.Books.SingleOrDefault(b => b.ID == bookId);
book.BookName = name;
entities.SaveChanges();
}
}
catch
{
throw new FaultException("Something went wrong");
}
}
public void DeleteBook(string id)
{
try
{
int bookId = Convert.ToInt32(id);
using (SampleDbEntities entities = new SampleDbEntities())
{
Book book = entities.Books.SingleOrDefault(b => b.ID == bookId);
entities.Books.DeleteObject(book);
entities.SaveChanges();
}
}
catch
{
throw new FaultException("Something went wrong");
}
}
}
Restful WCF 服務配置
現在從 ServiceContract 透檢視中,服務已準備好為 REST 請求提供服務,但是為了在休息時訪問此服務,我們還需要對服務行為和繫結進行一些更改。
要使服務通過 REST 協議可用,需要使用的繫結是 webHttpBinding。此外,我們需要設定端點的行為配置並在 endpointBehavior 中定義 webHttp 引數。所以我們的結果配置如下: