zl程序教程

您现在的位置是:首页 >  后端

当前栏目

ASP.NETWebAPI教程创建Admin控制器实例分享

实例ASP教程 创建 分享 控制器 admin NETWebAPI
2023-06-13 09:14:40 时间
Inthissection,we"lladdaWebAPIcontrollerthatsupportsCRUD(create,read,update,anddelete)operationsonproducts.ThecontrollerwilluseEntityFrameworktocommunicatewiththedatabaselayer.Onlyadministratorswillbeabletousethiscontroller.Customerswillaccesstheproductsthroughanothercontroller.
在本小节中,我们要添加一个对产品支持CRUD(创建、读取、更新和删除)操作的WebAPI控制器。该控制器将使用实体框架与数据库层进行通信。只有管理员才能够使用这个控制器。客户端将通过另一个控制器访问产品。
InSolutionExplorer,right-clicktheControllersfolder.SelectAddandthenController.
在“解决方案资源管理器”中右击Controllers文件夹,选择“添加”,然后选“控制器”(见图2-16)。
 
图2-16.添加控制器
IntheAddControllerdialog,namethecontrollerAdminController.UnderTemplate,select"APIcontrollerwithread/writeactions,usingEntityFramework".UnderModelclass,select"Product(ProductStore.Models)".UnderDataContext,select"<NewDataContext>".
在“添加控制器”对话框中,将此控制器命名为AdminController。在“模板”下选择“带有读/写动作的API控制器(用实体框架)”。在“模型类”下选择“Product(ProductStore.Models)”。在“数据上下文”下选择“<新数据上下文>”(见图2-17)。
 
图2-17.添加控制器对话框中的设置
IftheModelclassdrop-downdoesnotshowanymodelclasses,makesureyoucompiledtheproject.EntityFrameworkusesreflection,soitneedsthecompiledassembly.
如果“模型类”下拉列表未显示任何模型类,请确保已编译了此项目。实体框架使用反射,因此它需要已编译的程序集。
Selecting"<NewDataContext>"willopentheNewDataContextdialog.NamethedatacontextProductStore.Models.OrdersContext.
选择“<新数据上下文>”会打开“新数据上下文”对话框。将该数据上下文命名为ProductStore.Models.OrdersContext(见图2-18)。
 
图2-18.命名“新数据上下文”
ClickOKtodismisstheNewDataContextdialog.IntheAddControllerdialog,clickAdd.
点击“OK”退出这个“新数据上下文”对话框。在“添加控制器”对话框中点击“添加”。
Here"swhatgotaddedtotheproject:
以下是添加到项目的内容:
AclassnamedOrdersContextthatderivesfromDbContext.ThisclassprovidesthegluebetweenthePOCOmodelsandthedatabase.
一个名称为的OrdersContext类,它派生于DbContext。这个类提供了POCO模型与数据库之间的粘合。
AWebAPIcontrollernamedAdminController.ThiscontrollersupportsCRUDoperationsonProductinstances.ItusestheOrdersContextclasstocommunicatewithEntityFramework.
一个名称为AdminController的WebAPI控制器。这个控制器支持对Product实例的CRUD操作。它使用OrdersContext类与实体框架进行通信。
AnewdatabaseconnectionstringintheWeb.configfile.
Web.config文件中的一个新的数据库连接字符串。
上述新添加项见图2-19。
 
图2-19.新添加到项目的内容
OpentheOrdersContext.csfile.Noticethattheconstructorspecifiesthenameofthedatabaseconnectionstring.ThisnamereferstotheconnectionstringthatwasaddedtoWeb.config.
打开OrdersContext.cs文件。注意,其构造器指明了数据库连接字符串的名称。该名称是指被添加到Web.config的连接字符串。
复制代码代码如下:

publicOrdersContext():base("name=OrdersContext")AddthefollowingpropertiestotheOrdersContextclass:

将以下属性添加到OrdersContext类:
复制代码代码如下:

publicDbSet<Order>Orders{get;set;}
publicDbSet<OrderDetail>OrderDetails{get;set;}

ADbSetrepresentsasetofentitiesthatcanbequeried.HereisthecompletelistingfortheOrdersContextclass:
DbSet表示一组能够被查询的实体。以下是这个OrdersContext类的完整清单:
复制代码代码如下:
publicclassOrdersContext:DbContext
{
publicOrdersContext():base("name=OrdersContext")
{
}
publicDbSet<Order>Orders{get;set;}
publicDbSet<OrderDetail>OrderDetails{get;set;}
publicDbSet<Product>Products{get;set;}
}

TheAdminControllerclassdefinesfivemethodsthatimplementbasicCRUDfunctionality.EachmethodcorrespondstoaURIthattheclientcaninvoke:
类定义了实现基本的CRUD功能的五个方法。每个方法对应于一个客户端可以请求的URI(见表2-2):
表2-2.AdminController中实现CRUD操作的五个方法
table
EachmethodcallsintoOrdersContexttoquerythedatabase.Themethodsthatmodifythecollection(PUT,POST,andDELETE)calldb.SaveChangestopersistthechangestothedatabase.ControllersarecreatedperHTTPrequestandthendisposed,soitisnecessarytopersistchangesbeforeamethodreturns.
每一个方法调用都会进入OrdersContext对数据库进行查询。对数据集进行修改的方法(PUT、POST以及DELETE)会调用db.SaveChanges,以便把这些修改持久化回数据库。每个HTTP请求都会创建控制器(实例),然后清除它。因此,在一个方法返回之前,对修改持久化是必要的。
AddaDatabaseInitializer
添加数据库初始化器
EntityFrameworkhasanicefeaturethatletsyoupopulatethedatabaseonstartup,andautomaticallyrecreatethedatabasewheneverthemodelschange.Thisfeatureisusefulduringdevelopment,becauseyoualwayshavesometestdata,evenifyouchangethemodels.
实体框架有一个很好的特性,它让你在(应用程序)启动时填充数据库,并在模型发生修改时重建数据库。这个特性在开发期间是有用的,因为你总会有一些测试数据,甚至会修改模型。
InSolutionExplorer,right-clicktheModelsfolderandcreateanewclassnamedOrdersContextInitializer.Pasteinthefollowingimplementation:
在“解决方案资源管理器”中,右击Models文件夹,并创建一个名称为OrdersContextInitializer的新类。粘贴以下实现:
复制代码代码如下:
namespaceProductStore.Models
{
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Data.Entity;
publicclassOrdersContextInitializer:DropCreateDatabaseIfModelChanges<OrdersContext>
{
protectedoverridevoidSeed(OrdersContextcontext)
{
varproducts=newList<Product>()
{
newProduct(){Name="TomatoSoup",Price=1.39M,ActualCost=.99M},
newProduct(){Name="Hammer",Price=16.99M,ActualCost=10},
newProduct(){Name="Yoyo",Price=6.99M,ActualCost=2.05M}
};
products.ForEach(p=>context.Products.Add(p));
context.SaveChanges();
varorder=newOrder(){Customer="Bob"};
varod=newList<OrderDetail>()
{
newOrderDetail(){Product=products[0],Quantity=2,Order=order},
newOrderDetail(){Product=products[1],Quantity=4,Order=order}
};
context.Orders.Add(order);
od.ForEach(o=>context.OrderDetails.Add(o));
context.SaveChanges();
}
}
}

ByinheritingfromtheDropCreateDatabaseIfModelChangesclass,wearetellingEntityFrameworktodropthedatabasewheneverwemodifythemodelclasses.WhenEntityFrameworkcreates(orrecreates)thedatabase,itcallstheSeedmethodtopopulatethetables.WeusetheSeedmethodtoaddsomeexampleproductsplusanexampleorder.
通过对DropCreateDatabaseIfModelChanges类的继承,我们是在告诉实体框架,无论何时修改了模型类,便删除数据库。当实体框架创建(或重建)数据库时,它会调用Seed方法去填充数据库。我们用这个Seed方法添加了一些例子产品和一个例子订单。
Thisfeatureisgreatfortesting,butdon"tusetheDropCreateDatabaseIfModelChangesclassinproduction,becauseyoucouldloseyourdataifsomeonechangesamodelclass.
这个特性对于测试是很棒的,但在产品(指正式运行的应用程序—译者注)中不要使用这个DropCreateDatabaseIfModelChanges类。因为,如果有人修改了模型类,便会丢失数据。
Next,openGlobal.asaxandaddthefollowingcodetotheApplication_Startmethod:
下一步,打开Global.asax,并将以下代码添加到Application_Start方法中:
复制代码代码如下:
System.Data.Entity.Database.SetInitializer(
newProductStore.Models.OrdersContextInitializer());SendaRequesttotheController

向控制器发送请求
Atthispoint,wehaven"twrittenanyclientcode,butyoucaninvokethewebAPIusingawebbrowseroranHTTPdebuggingtoolsuchasFiddler.InVisualStudio,pressF5tostartdebugging.Yourwebbrowserwillopentohttp://localhost:portnum/,whereportnumissomeportnumber.
此刻,我们还没有编写任何客户端代码,但你已经可以使用Web浏览器或诸如Fiddler之类的调试工具来调用这个WebAPI了。在VisualStudio中按F5键启动调试。你的浏览器将打开网址http://localhost:portnum/,这里,portnum是某个端口号。
SendanHTTPrequestto"http://localhost:portnum/api/admin".Thefirstrequestmaybeslowtocomplete,becauseEntifyEntityFrameworkneedstocreateandseedthedatabase.Theresponseshouldsomethingsimilartothefollowing:
发送一个HTTP请求到“http://localhost:portnum/api/admin”。第一次请求可能会慢一些才能完成,因为实体框架需要创建和种植数据库。其响应应当类似于下面这样:
复制代码代码如下:
HTTP/1.1200OK
Server:ASP.NETDevelopmentServer/10.0.0.0
Date:Mon,18Jun201204:30:33GMT
X-AspNet-Version:4.0.30319
Cache-Control:no-cache
Pragma:no-cache
Expires:-1
Content-Type:application/json;charset=utf-8
Content-Length:175
Connection:Close
[{"Id":1,"Name":"TomatoSoup","Price":1.39,"ActualCost":0.99},{"Id":2,"Name":"Hammer",
"Price":16.99,"ActualCost":10.00},{"Id":3,"Name":"Yoyo","Price":6.99,"ActualCost":
2.05}]

看完此文如果觉得有所收获,恳请给个推荐