Skip to content

Instantly share code, notes, and snippets.

@raghuramn
Created September 10, 2013 19:13
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/6514170 to your computer and use it in GitHub Desktop.
Save raghuramn/6514170 to your computer and use it in GitHub Desktop.
using System;
using System.ComponentModel.DataAnnotations;
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;
namespace ValidateDelta
{
class Program
{
static void Main(string[] args)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Customer>("Customers");
HttpServer server = new HttpServer();
server.Configuration.Routes.MapODataRoute("odata", "", builder.GetEdmModel());
HttpClient client = new HttpClient(server);
var request = new HttpRequestMessage(new HttpMethod("Patch"), "http://localhost/Customers(42)");
request.Content = new StringContent("{ }", Encoding.Default, "application/json");
var response = client.SendAsync(request).Result;
Console.WriteLine(response);
if (response.Content != null)
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
}
}
public class CustomersController : ODataController
{
public void Patch(Delta<Customer> delta)
{
Customer c = new Customer();
delta.Patch(c);
Validate(c, typeof(Customer));
}
private void Validate(object model, Type type)
{
var validator = Configuration.Services.GetBodyModelValidator();
var metadataProvider = Configuration.Services.GetModelMetadataProvider();
HttpActionContext actionContext = new HttpActionContext(ControllerContext, Request.GetActionDescriptor());
if (!validator.Validate(model, type, metadataProvider, actionContext, String.Empty))
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState));
}
}
}
public class Customer
{
public int ID { get; set; }
[Required]
public string Name { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment