Skip to content

Instantly share code, notes, and snippets.

@raghuramn
Last active December 19, 2015 05:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raghuramn/5903008 to your computer and use it in GitHub Desktop.
Save raghuramn/5903008 to your computer and use it in GitHub Desktop.
using Microsoft.Data.Edm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Routing;
using System.Web.Http.OData.Routing.Conventions;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
HttpServer server = new HttpServer();
var routingConventions = ODataRoutingConventions.CreateDefault();
routingConventions.Insert(0, new CreateNavigationPropertyRoutingConvention());
server.Configuration.Routes.MapODataRoute("odata", "", GetEdmModel(), new DefaultODataPathHandler(), routingConventions);
HttpClient client = new HttpClient(server);
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customers(42)/Orders");
request.Content = new StringContent("{ 'ID' : 42 }", Encoding.Default, "application/json");
var response = client.SendAsync(request).Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
builder.EntitySet<Order>("Orders");
return builder.GetEdmModel();
}
}
public class CustomersController : ODataController
{
public HttpResponseMessage PostToOrders([FromODataUri] int key, Order order)
{
// create order.
return Request.CreateResponse(HttpStatusCode.Created, order);
}
}
public class Customer
{
public int ID { get; set; }
public IList<Order> Orders { get; set; }
}
public class Order
{
public int ID { get; set; }
}
// routing convention to handle POST requests to navigation properties.
public class CreateNavigationPropertyRoutingConvention : EntitySetRoutingConvention
{
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
{
if (odataPath.PathTemplate == "~/entityset/key/navigation" && controllerContext.Request.Method == HttpMethod.Post)
{
IEdmNavigationProperty navigationProperty = (odataPath.Segments[2] as NavigationPathSegment).NavigationProperty;
controllerContext.RouteData.Values["key"] = (odataPath.Segments[1] as KeyValuePathSegment).Value; // set the key for model binding.
return "PostTo" + navigationProperty.Name;
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment