Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Custom Action in an EntitySetController

I have an oData application in .Net 4.5. oData end points are working fine, but I want to create a custom action on the controller to set a flag on a Customer record when given an email address.

Here is my client code (using AngularJS):

    $http({
        method: 'POST',
        url: '/odata/Customers/SetAlertFlag',
        data: { 'email': '[email protected]'}
    }).success(function (data, status, headers, config) {
        // ...
    }).error(function (data, status, headers, config) {
        // ...
    });

Here is my server code:

public class CustomersController : EntitySetController<Customer, int>
{
    private DBEntities db = new DBEntities();

    // ... other generated methods here


    // my custom method
    [HttpPut]
    public Boolean SetAlertFlag([FromBody] string email)
    {
        return true;
    }
}

The server method never gets called. When I type this URL in the browser http://localhost:60903/odata/Customers/SetAlertFlag I get this error: "Invalid action detected. 'SetAlertFlag' is not an action that can bind to 'Collection([Skirts.Models.Customer Nullable=False])'."

Can EntitySetController classes not have custom methods? How else should I do this?

like image 437
Brent Engwall Avatar asked Mar 22 '23 09:03

Brent Engwall


1 Answers

Actions in OData use a specific format, and need to be POST. You need to:

Add the action to the EDM:

ActionConfiguration action = modelBuilder.Entity<Customer>().Collection.Action("SetAlertFlag");
action.Parameter<string>("email");

Declare the action like this:

[HttpPost]
public int SetAlertFlag(ODataActionParameters parameters) 
{ 
    if (!ModelState.IsValid)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    string email = (string)parameters["email"];
}

Invoke the action something like this:

POST http://localhost/odata/Customers/SetAlertFlag
Content-Type: application/json

{"email":"foo"}

Read more here: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-actions

(I just typed these code snippets, so may be some errors, but that's the idea.)

like image 115
Mike Wasson Avatar answered Apr 02 '23 15:04

Mike Wasson