Reputation: 5
I was trying to define a Post OData Web API action.The parameter is a number. I found an article And I followed as the article described, here is the source code:
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MapODataServiceRoute("odata", "odata", model: GetModel());
}
private static Microsoft.OData.Edm.IEdmModel GetModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<ThumbnailQueue>("ThumbnailQueues");
builder.EntitySet<Document>("Documents");
EntitySetConfiguration<ThumbnailQueue> thumbnailQueue = builder.EntitySet<ThumbnailQueue>("ThumbnailQueues");
var action = thumbnailQueue.EntityType.Action("PostThumbnailQueue");
action.Parameter<long>("DocumentSN");
var postThumbnailQueue = thumbnailQueue.EntityType.Collection.Action("PostThumbnailQueue");
postThumbnailQueue.Parameter<long>("DocumentSN");
return builder.GetEdmModel();
}
}
Web API
public class ThumbnailQueuesController : ODataController
{
private MarketingEntities db = new MarketingEntities();
// POST: odata/ThumbnailQueues
[HttpPost]
public IHttpActionResult PostThumbnailQueue(ODataActionParameters parameters)
{
if (parameters == null) return BadRequest();
var documentSN = (long)parameters["DocumentSN"];
if (db.ThumbnailQueues.Any(t => t.DocumentSN == documentSN))
{
return BadRequest("Record already exists");
}
var myThumbnailQueue = new ThumbnailQueue();
myThumbnailQueue.DocumentSN = documentSN;
myThumbnailQueue.Status = 1;
db.ThumbnailQueues.Add(myThumbnailQueue);
db.SaveChanges();
return Ok();
}
I used Postman to test the function
But in the run time, the parameter is null, so I can not get documentSN from the parameter. I have troubleshoot this porblem for hours, could anybody help me to fix this problem? Many thanks~
Upvotes: 0
Views: 2858
Reputation: 6090
You need to use the following route for that: http://localhost:10076/odata/ThumbnailQueues/Default.PostThumbnailQueue
Upvotes: 1