"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Supporting OData Actions in ASP.NET Web API 2

by Mike Wasson

Download Completed Project

In OData, actions are a way to add server-side behaviors that are not easily defined as CRUD operations on entities. Some uses for actions include:

  • Implementing complex transactions.
  • Manipulating several entities at once.
  • Allowing updates only to certain properties of an entity.
  • Sending information to the server that is not defined in an entity.

Software versions used in the tutorial

  • Web API 2
  • OData Version 3
  • Entity Framework 6

Example: Rating a Product

In this example, we want to let users rate products, and then expose the average ratings for each product. On the database, we will store a list of ratings, keyed to products.

Here is the model we might use to represent the ratings in Entity Framework:

[!code-csharpMain]

   1:  public class ProductRating
   2:  {
   3:      public int ID { get; set; }
   4:   
   5:      [ForeignKey("Product")]
   6:      public int ProductID { get; set; }
   7:      public virtual Product Product { get; set; }  // Navigation property
   8:   
   9:      public int Rating { get; set; }
  10:  }

But we don’t want clients to POST a ProductRating object to a “Ratings” collection. Intuitively, the rating is associated with the Products collection, and the client should only need to post the rating value.

Therefore, instead of using the normal CRUD operations, we define an action that a client can invoke on a Product. In OData terminology, the action is bound to Product entities.

Actions have side-effects on the server. For this reason, they are invoked using HTTP POST requests. Actions can have parameters and return types, which are described in the service metadata. The client sends the parameters in the request body, and the server sends the return value in the response body. To invoke the “Rate Product” action, the client sends a POST to a URI like the following:

[!code-consoleMain]

   1:  http://localhost/odata/Products(1)/RateProduct

The data in the POST request is simply the product rating:

[!code-consoleMain]

   1:  {"Rating":2}

Declare the Action in the Entity Data Model

In your Web API configuration, add the action to the entity data model (EDM):

[!code-csharpMain]

   1:  public static class WebApiConfig
   2:  {
   3:      public static void Register(HttpConfiguration config)
   4:      {
   5:          ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
   6:          builder.EntitySet<Product>("Products");
   7:          builder.EntitySet<Supplier>("Suppliers");
   8:          builder.EntitySet<ProductRating>("Ratings");
   9:   
  10:          // New code: Add an action to the EDM, and define the parameter and return type.
  11:          ActionConfiguration rateProduct = builder.Entity<Product>().Action("RateProduct");
  12:          rateProduct.Parameter<int>("Rating");
  13:          rateProduct.Returns<double>();
  14:   
  15:          config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
  16:      }
  17:  }

This code defines “RateProduct” as an action that can be performed on Product entities. It also declares that the action takes an int parameter named “Rating”, and returns an int value.

Add the Action to the Controller

The “RateProduct” action is bound to Product entities. To implement the action, add a method named RateProduct to the Products controller:

[!code-csharpMain]

   1:  [HttpPost]
   2:  public async Task<IHttpActionResult> RateProduct([FromODataUri] int key, ODataActionParameters parameters)
   3:  {
   4:      if (!ModelState.IsValid)
   5:      {
   6:          return BadRequest();
   7:      }
   8:   
   9:      int rating = (int)parameters["Rating"];
  10:   
  11:      Product product = await db.Products.FindAsync(key);
  12:      if (product == null)
  13:      {
  14:          return NotFound();
  15:      }
  16:   
  17:      product.Ratings.Add(new ProductRating() { Rating = rating });
  18:      db.SaveChanges();
  19:   
  20:      double average = product.Ratings.Average(x => x.Rating);
  21:   
  22:      return Ok(average);
  23:  }

Notice that the method name matches the name of the action in the EDM. The method has two parameters:

If you are using the default routing conventions, the key parameter must be named “key”. It is also important to include the [FromOdataUri] attribute, as shown. This attribute tells Web API to use OData syntax rules when it parses the key from the request URI.

Use the parameters dictionary to get the action parameters:

[!code-csharpMain]

   1:  if (!ModelState.IsValid)
   2:  {
   3:      return BadRequest();
   4:  }
   5:  int rating = (int)parameters["Rating"];

If the client sends the action parameters in the correct format, the value of ModelState.IsValid is true. In that case, you can use the ODataActionParameters dictionary to get the parameter values. In this example, the RateProduct action takes a single parameter named “Rating”.

Action Metadata

To view the service metadata, send a GET request to /odata/$metadata. Here is the portion of the metadata that declares the RateProduct action:

[!code-xmlMain]

   1:  <FunctionImport Name="RateProduct" m:IsAlwaysBindable="true" IsBindable="true" ReturnType="Edm.Double">
   2:    <Parameter Name="bindingParameter" Type="ProductService.Models.Product"/>
   3:    <Parameter Name="Rating" Nullable="false" Type="Edm.Int32"/>
   4:  </FunctionImport>

The FunctionImport element declares the action. Most of the fields are self-explanatory, but two are worth noting:

The difference is that some actions are always available to clients, but other actions might depend on the state of the entity. For example, suppose you define a “Purchase” action. You can only purchase an item that is in stock. If the item is out of stock, a client cannot invoke that action.

When you define the EDM, the Action method creates an always-bindable action:

[!code-csharpMain]

   1:  builder.Entity<Product>().Action("RateProduct"); // Always bindable

I’ll talk about not-always-bindable actions (also called transient actions) later in this topic.

Invoking the Action

Now let’s see how a client would invoke this action. Suppose the client wants to give a rating of 2 to the product with ID = 4. Here is an example request message, using JSON format for the request body:

[!code-consoleMain]

   1:  POST http://localhost/odata/Products(4)/RateProduct HTTP/1.1
   2:  Content-Type: application/json
   3:  Content-Length: 12
   4:   
   5:  {"Rating":2}

Here is the response message:

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Content-Type: application/json; charset=utf-8
   3:  DataServiceVersion: 3.0
   4:  Date: Tue, 22 Oct 2013 19:04:00 GMT
   5:  Content-Length: 89
   6:   
   7:  {
   8:    "odata.metadata":"http://localhost:21900/odata/$metadata#Edm.Double","value":2.75
   9:  }

Binding an Action to an Entity Set

In the previous example, the action is bound to a single entity: The client rates a single product. You can also bind an action to a collection of entities. Just make the following changes:

In the EDM, add the action to the entity’s Collection property.

[!code-csharpMain]

   1:  var rateAllProducts = builder.Entity<Product>().Collection.Action("RateAllProducts");

In the controller method, omit the key parameter.

[!code-csharpMain]

   1:  [HttpPost]
   2:  public int RateAllProducts(ODataActionParameters parameters)
   3:  {
   4:      // ....
   5:  }

Now the client invokes the action on the Products entity set:

[!code-consoleMain]

   1:  http://localhost/odata/Products/RateAllProducts

Actions with Collection Parameters

Actions can have parameters that take a collection of values. In the EDM, use CollectionParameter<T> to declare the parameter.

[!code-csharpMain]

   1:  rateAllProducts.CollectionParameter<int>("Ratings");

This declares a parameter named “Ratings” that takes a collection of int values. In the controller method, you still get the parameter value from the ODataActionParameters object, but now the value is an ICollection<int> value:

[!code-csharpMain]

   1:  [HttpPost]
   2:  public void RateAllProducts(ODataActionParameters parameters)
   3:  {
   4:      if (!ModelState.IsValid)
   5:      {
   6:          throw new HttpResponseException(HttpStatusCode.BadRequest);
   7:      }
   8:   
   9:      var ratings = parameters["Ratings"] as ICollection<int>; 
  10:   
  11:      // ...
  12:  }

Transient Actions

In the “RateProduct” example, users can always rate a product, so the action is always available. But some actions depend on the state of the entity. For example, in a video rental service, the “CheckOut” action is not always available. (It depends whether a copy of that video is available.) This type of action is called a transient action.

In the service metadata, a transient action has IsAlwaysBindable equal to false. That’s actually the default value, so the metadata will look like this:

[!code-xmlMain]

   1:  <FunctionImport Name="CheckOut" IsBindable="true">
   2:      <Parameter Name="bindingParameter" Type="ProductsService.Models.Product" />
   3:  </FunctionImport>

Here’s why this matters: If an action is transient, the server needs to tell the client when the action is available. It does this by including a link to the action in the entity. Here is an example for a Movie entity:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost:17916/odata/$metadata#Movies/@Element",
   3:    "#CheckOut":{ "target":"http://localhost:17916/odata/Movies(1)/CheckOut" },
   4:    "ID":1,"Title":"Sudden Danger 3","Year":2012,"Genre":"Action"
   5:  }

The “#CheckOut” property contains a link to the CheckOut action. If the action is not available, the server omits the link.

To declare a transient action in the EDM, call the TransientAction method:

[!code-csharpMain]

   1:  var checkoutAction = builder.Entity<Movie>().TransientAction("CheckOut");

Also, you must provide a function that returns an action link for a given entity. Set this function by calling HasActionLink. You can write the function as a lambda expression:

[!code-csharpMain]

   1:  checkoutAction.HasActionLink(ctx =>
   2:  {
   3:      var movie = ctx.EntityInstance as Movie;
   4:      if (movie.IsAvailable) {
   5:          return new Uri(ctx.Url.ODataLink(
   6:              new EntitySetPathSegment(ctx.EntitySet), 
   7:              new KeyValuePathSegment(movie.ID.ToString()),
   8:              new ActionPathSegment(checkoutAction.Name)));
   9:      }
  10:      else
  11:      {
  12:          return null;
  13:      }
  14:  }, followsConventions: true);

If the action is available, the lambda expression returns a link to the action. The OData serializer includes this link when it serializes the entity. When the action is not available, the function returns null.

Additional Resources

OData Actions Sample



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/odata-actions.htm
< THANKS ME>