|
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; |
|
} |
|
} |
|
} |