欢迎来到天天文库
浏览记录
ID:6083170
大小:101.00 KB
页数:10页
时间:2018-01-02
《创建产品和订单控制器》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、【ASP.NETWebAPI教程】2.3.6创建产品和订单控制器注:本文是【ASP.NETWebAPI系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。Part6:CreatingProductandOrderControllers第6部分:创建产品和订单控制器本文引自:http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-6AddaProductsController添
2、加产品控制器TheAdmincontrollerisforuserswhohaveadministratorprivileges.Customers,ontheotherhand,canviewproductsbutcannotcreate,update,ordeletethem.Admin控制器是用于具有管理员权限的用户的。另一方面,一般客户可以查看产品,但不能创建、更新或删除。WecaneasilyrestrictaccesstothePost,Put,andDeletemethods,whileleavingtheGetmethodsopen.Butlookatthedatathatis
3、returnedforaproduct:我们可以很容易地对Post、Put和Delete方法进行限制访问,而只让Get方法是开放的。但先看一看针对一个产品所返回的数据:{"Id":1,"Name":"TomatoSoup","Price":1.39,"ActualCost":0.99}TheActualCostpropertyshouldnotbevisibletocustomers!Thesolutionistodefineadatatransferobject(DTO)thatincludesasubsetofpropertiesthatshouldbevisibletocustomers
4、.WewilluseLINQtoprojectProductinstancestoProductDTOinstances.ActualCost(实际开销,指该产品的成本—译者注)属性不应该是客户可见的。其解决方案是定义包含属性子集的、客户可见的一个datatransferobject(DTO—数据传输对象)。我们将用LINQ把Product实例投影到ProductDTO实例。AddaclassnamedProductDTOtotheModelsfolder.添加一个名称为ProductDTO的类到Models文件夹:namespaceProductStore.Models{publicclas
5、sProductDTO{publicintId{get;set;}publicstringName{get;set;}publicdecimalPrice{get;set;}}}Nowaddthecontroller.InSolutionExplorer,right-clicktheControllersfolder.SelectAdd,thenselectController.IntheAddControllerdialog,namethecontroller"ProductsController".UnderTemplate,selectEmptyAPIcontroller.现在添加控制器
6、。在“解决方案资源管理器”中右击Controllers文件夹。选择“添加”,然后选择“控制器”。在“添加控制器”对话框中,将此控制器命名为“ProductsController”。在“模板”的下面选择“空的API控制器”(见图2-24)。图2-24.添加ProductsController控制器Replaceeverythinginthesourcefilewiththefollowingcode:用以下代码替换源文件的全部内容:namespaceProductStore.Controllers{usingSystem.Collections.Generic;usingSystem.Linq;
7、usingSystem.Net;usingSystem.Net.Http;usingSystem.Web.Http;usingProductStore.Models;publicclassProductsController:ApiController{privateOrdersContextdb=newOrdersContext();//ProjectproductstoproductDTOs.
此文档下载收益归作者所有