wcf WCF Resful服务

示例

[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");

        }

    }

}

宁静的WCF服务配置

现在,从ServiceContract角度来看,该服务已准备就绪,可以处理REST请求,但是要在其余时间访问该服务,我们还需要对服务行为和绑定进行一些更改。

为了使服务可以通过REST协议使用,需要使用的绑定是webHttpBinding。另外,我们需要设置端点的行为配置,并在endpointBehavior中定义webHttp参数。因此,我们得到的配置将类似于:

以上是 wcf WCF Resful服务 的全部内容, 来源链接: utcz.com/z/340658.html

回到顶部