Actions and Functions in OData v4 Using ASP.NET Web API 2.2
by Mike Wasson
In OData, actions and functions are a way to add server-side behaviors that are not easily defined as CRUD operations on entities. This tutorial shows how to add actions and functions to an OData v4 endpoint, using Web API 2.2. The tutorial builds on the tutorial Create an OData v4 Endpoint Using ASP.NET Web API 2
Software versions used in the tutorial
- Web API 2.2
- OData v4
- Visual Studio 2013 Update 2
- .NET 4.5
Tutorial versions
For OData Version 3, see OData Actions in ASP.NET Web API 2.
The difference between actions and functions is that actions can have side effects, and functions do not. Both actions and functions can return data. Some uses for actions include:
- Complex transactions.
- Manipulating several entities at once.
- Allowing updates only to certain properties of an entity.
- Sending data that is not an entity.
Functions are useful for returning information that does not correspond directly to an entity or collection.
An action (or function) can target a single entity or a collection. In OData terminology, this is the binding. You can also have “unbound” actions/functions, which are called as static operations on the service.
Example: Adding an Action
Let’s define an action to rate a product.
[!NOTE] This tutorial builds on the tutorial Create an OData v4 Endpoint Using ASP.NET Web API 2
First, add a ProductRating
model to represent the ratings.
[!code-csharpMain]
1: namespace ProductService.Models
2: {
3: public class ProductRating
4: {
5: public int ID { get; set; }
6: public int Rating { get; set; }
7: public int ProductID { get; set; }
8: public virtual Product Product { get; set; }
9: }
10: }
Also add a DbSet to the ProductsContext
class, so that EF will create a Ratings table in the database.
[!code-csharpMain]
1: public class ProductsContext : DbContext
2: {
3: public ProductsContext()
4: : base("name=ProductsContext")
5: {
6: }
7:
8: public DbSet<Product> Products { get; set; }
9: public DbSet<Supplier> Suppliers { get; set; }
10: // New code:
11: public DbSet<ProductRating> Ratings { get; set; }
12: }
Add the Action to the EDM
In WebApiConfig.cs, add the following code:
[!code-csharpMain]
1: ODataModelBuilder builder = new ODataConventionModelBuilder();
2: builder.EntitySet<Product>("Products");
3:
4: // New code:
5: builder.Namespace = "ProductService";
6: builder.EntityType<Product>()
7: .Action("Rate")
8: .Parameter<int>("Rating");
The EntityTypeConfiguration.Action method adds an action to the entity data model (EDM). The Parameter method specifies a typed parameter for the action.
This code also sets the namespace for the EDM. The namespace matters because the URI for the action includes the fully-qualified action name:
[!code-consoleMain]
1: http://localhost/Products(1)/ProductService.Rate
[!NOTE] In a typical IIS configuration, the dot in this URL will cause IIS to return error 404. You can resolve this by adding the following section to your Web.Config file:
[!code-xmlMain]
1: <system.webServer>
2: <handlers>
3: <clear/>
4: <add name="ExtensionlessUrlHandler-Integrated-4.0" path="/*"
5: verb="*" type="System.Web.Handlers.TransferRequestHandler"
6: preCondition="integratedMode,runtimeVersionv4.0" />
7: </handlers>
8: </system.webServer>
Add a Controller Method for the Action
To enable the “Rate” action, add the following method to ProductsController
:
[!code-csharpMain]
1: [HttpPost]
2: public async Task<IHttpActionResult> Rate([FromODataUri] int key, ODataActionParameters parameters)
3: {
4: if (!ModelState.IsValid)
5: {
6: return BadRequest();
7: }
8:
9: int rating = (int)parameters["Rating"];
10: db.Ratings.Add(new ProductRating
11: {
12: ProductID = key,
13: Rating = rating
14: });
15:
16: try
17: {
18: await db.SaveChangesAsync();
19: }
20: catch (DbUpdateException e)
21: {
22: if (!ProductExists(key))
23: {
24: return NotFound();
25: }
26: else
27: {
28: throw;
29: }
30: }
31:
32: return StatusCode(HttpStatusCode.NoContent);
33: }
Notice that the method name matches the action name. The [HttpPost] attribute specifies the method is an HTTP POST method.
To invoke the action, the client sends an HTTP POST request like the following:
[!code-consoleMain]
1: POST http://localhost/Products(1)/ProductService.Rate HTTP/1.1
2: Content-Type: application/json
3: Content-Length: 12
4:
5: {"Rating":5}
The “Rate” action is bound to Product instances, so the URI for the action is the fully-qualified action name appended to the entity URI. (Recall that we set the EDM namespace to “ProductService”, so the fully-qualified action name is “ProductService.Rate”.)
The body of the request contains the action parameters as a JSON payload. Web API automatically converts the JSON payload to an ODataActionParameters object, which is just a dictionary of parameter values. Use this dictionary to access the parameters in your controller method.
If the client sends the action parameters in the wrong format, the value of ModelState.IsValid is false. Check this flag in your controller method and return an error if IsValid is false.
[!code-csharpMain]
1: if (!ModelState.IsValid)
2: {
3: return BadRequest();
4: }
Example: Adding a Function
Now let’s add an OData function that returns the most expensive product. As before, the first step is adding the function to the EDM. In WebApiConfig.cs, add the following code.
[!code-csharpMain]
1: ODataModelBuilder builder = new ODataConventionModelBuilder();
2: builder.EntitySet<Product>("Products");
3: builder.EntitySet<Supplier>("Suppliers");
4:
5: // New code:
6: builder.Namespace = "ProductService";
7: builder.EntityType<Product>().Collection
8: .Function("MostExpensive")
9: .Returns<double>();
In this case, the function is bound to the Products collection, rather than individual Product instances. Clients invoke the function by sending a GET request:
[!code-consoleMain]
1: GET http://localhost:38479/Products/ProductService.MostExpensive
Here is the controller method for this function:
[!code-csharpMain]
1: public class ProductsController : ODataController
2: {
3: [HttpGet]
4: public IHttpActionResult MostExpensive()
5: {
6: var product = db.Products.Max(x => x.Price);
7: return Ok(product);
8: }
9:
10: // Other controller methods not shown.
11: }
Notice that the method name matches the function name. The [HttpGet] attribute specifies the method is an HTTP GET method.
Here is the HTTP response:
[!code-consoleMain]
1: HTTP/1.1 200 OK
2: Content-Type: application/json; odata.metadata=minimal; odata.streaming=true
3: OData-Version: 4.0
4: Date: Sat, 28 Jun 2014 00:44:07 GMT
5: Content-Length: 85
6:
7: {
8: "@odata.context":"http://localhost:38479/$metadata#Edm.Decimal","value":50.00
9: }
Example: Adding an Unbound Function
The previous example was a function bound to a collection. In this next example, we’ll create an unbound function. Unbound functions are called as static operations on the service. The function in this example will return the sales tax for a given postal code.
In the WebApiConfig file, add the function to the EDM:
[!code-csharpMain]
1: ODataModelBuilder builder = new ODataConventionModelBuilder();
2: builder.EntitySet<Product>("Products");
3:
4: // New code:
5: builder.Function("GetSalesTaxRate")
6: .Returns<double>()
7: .Parameter<int>("PostalCode");
Notice that we are calling Function directly on the ODataModelBuilder, instead of the entity type or collection. This tells the model builder that the function is unbound.
Here is the controller method that implements the function:
[!code-csharpMain]
1: [HttpGet]
2: [ODataRoute("GetSalesTaxRate(PostalCode={postalCode})")]
3: public IHttpActionResult GetSalesTaxRate([FromODataUri] int postalCode)
4: {
5: double rate = 5.6; // Use a fake number for the sample.
6: return Ok(rate);
7: }
It does not matter which Web API controller you place this method in. You could put it in ProductsController
, or define a separate controller. The [ODataRoute] attribute defines the URI template for the function.
Here is an example client request:
[!code-consoleMain]
1: GET http://localhost:38479/GetSalesTaxRate(PostalCode=10) HTTP/1.1
The HTTP response:
[!code-consoleMain]
1: HTTP/1.1 200 OK
2: Content-Type: application/json; odata.metadata=minimal; odata.streaming=true
3: OData-Version: 4.0
4: Date: Sat, 28 Jun 2014 01:05:32 GMT
5: Content-Length: 82
6:
7: {
8: "@odata.context":"http://localhost:38479/$metadata#Edm.Double","value":5.6
9: }
|