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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With