在ASP.NET Web API中使用OData的Action和Function
?
本篇體驗OData的Action和Function功能。上下文信息參考"ASP.NET Web API基于OData的增刪改查,以及處理實體間關系"。在本文之前,我存在的疑惑包括:
?
● 為什么需要OData的Action和Function功能?
● Action和Function之間有什么區別?
● 如何設置OData的的Action和Function功能?這中間有哪些慣例呢?
?
為某個Product添加Action
?
如果我們希望通過http://localhost:54714/odata/Products(1)/SomeActionName來實現在某個Product基礎上,為Product的關聯表ProductRating添加一條數據,該如何做到呢?
首先創建產品評論的一個模型:
?
public class ProductRating {public int ID { get; set; }public int Rating { get; set; }public int ProductID { get; set; }public virtual Product Product { get; set; } }?
把模型添加到上下文中:
?
public class ProductsContext : DbContext {public ProductsContext(): base("name=ProductsContext"){}public DbSet<Product> Products { get; set; }public DbSet<Supplier> Suppliers { get; set; }public DbSet<ProductRating> Ratings { get; set; } }?
添加遷移并更新數據庫:
Add-Migration "AddProductRating" -StartUpProjectName ProductService -ProjectName ProductService
Update-Database? -StartUpProjectName ProductService -ProjectName ProductService ?
現在,需要在WebApiConfig.cs中的Register方法中,為Product的EDM添加一個Action。
?
ODataModelBuilder builder = new ODataConventionModelBuilder(); builder.Namespace = "ProductService";builder.EntitySet<Product>("Products");//創建EntityDataModel(EDM) builder.EntitySet<Supplier>("Suppliers");//http://localhost/Products(1)/ProductService.Rate 注意需要在Web.config中添加配置,因為在IIS上不允許帶點,否則會返回404 builder.EntityType<Product>().Action("Rate")//給EDM添加一個Action.Parameter<int>("Rating"); //Rating作為參數在前后端傳遞 config.MapODataServiceRoute(routeName: "ODataRoute",routePrefix: "odata", model:builder.GetEdmModel());?
以上,
● 通過builder.Namespace定義了Action的命名空間為ProductService
● 通過Action方法給Product這個EDM定義了Rate這個Action
● 通過Parameter<T>方法定義了參數
這意味著:
● 我們發出的請求格式大致是:http://localhost:54714/odata/Products(1)/ProductService.Rate
● API的action方法中,action名稱是Rate,可以從前端接受一個名稱為Rating的鍵值
可問題還有:
● 前端如何把Rating這個參數傳遞出去呢?
● 后端又如何接受這個Rating參數呢?
來看后端控制器部分的action,在ProductsController中添加如下:
?
//這里的action名稱Rate必須和EDM定義的時候保持一致 [HttpPost] public async Task<IHttpActionResult> Rate([FromODataUri] int key, ODataActionParameters parameters) {//先驗證if(!ModelState.IsValid){return BadRequest();}//再取值int rating = (int)parameters["Rating"];//實施操作db.Ratings.Add(new ProductRating{ProductID = key,Rating = rating});//捕獲異常try{await db.SaveChangesAsync();}catch (DbUpdateException ex){if (!ProductExists(key)){return NotFound();}else{throw;}}return StatusCode(HttpStatusCode.NoContent);}?
可見,后端是通過ODataActionParameters來接受前端傳來的變量Rating。
現在前端可以試著發出請求了:
POST http://localhost:54714/odata/Products(1)/ProductService.Rate
Body {"Rating":5}
我們把Rating變量放在了Body中,以json傳遞給后端。
可是,返回結果是: 404 Not Found
這是因為,IIS還不接受類似ProductService.Rate這樣的寫法,在Web.config添加如下配置:
?
<system.webServer> <handlers>...<remove name="ExtensionlessUrlHandler-Integrated-4.0" /><add name="ExtensionlessUrlHandler-Integrated-4.0" path="/odata/*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer>?
重新請求,返回:204 No Content
?
為Product集合添加Action
?
如果想為Products集合添加如下方法發出如下請求:http://localhost:54714/odata/Products/ProductService.MostExpensive
首先還是配置EDM:
?
builder.EntityType<Product>().Collection.Function("MostExpensive").Returns<double>();?
在ProductsController中添加如下Action:
?
[HttpGet] public IHttpActionResult MostExpensive() {var product = db.Products.Max(x => x.Price);return Ok(product); }?
前端請求:
GET http://localhost:54714/odata/Products/ProductService.MostExpensive
返回:
{
? "@odata.context": "http://localhost:54714/odata/$metadata#Edm.Decimal",
? "value": 18.2
}
和EDM模型無關,添加Function
當我們需要添加一個與EDM 模型無關的方法時候,就使用Function。
首先在WebApi.config中配置如下:
?
在某個Controller中添加如下:
?
[HttpGet] [ODataRoute("GetSalesTaxRate(PostalCode={postalCode})")] public IHttpActionResult GetSalesTaxRate([FromODataUri] int postalCode) {double rate = 5.8;return Ok(rate); }?
以上,ODataRoute設定路由規則。前端發出如下請求:
GET http://localhost:54714/odata/GetSalesTaxRate(PostalCode=10)
返回:
{
? "@odata.context": "http://localhost:54714/odata/$metadata#Edm.Double",
? "value": 5.8
}
總結:當需要針對某個EDM模型或EDM模型集合進行CRUD以外的操作,甚至涉及多個模型的操作使用Action,但添加和EDM模型無關的操作,使用Function。
?
總結
以上是生活随笔為你收集整理的在ASP.NET Web API中使用OData的Action和Function的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分享一百多套开发视频教程的下载地址(转)
- 下一篇: iphone开发畅销书TOP5(chin