Created
May 10, 2013 19:13
-
-
Save raghuramn/5556691 to your computer and use it in GitHub Desktop.
$format message handler for web API OData.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Web.Http; | |
using System.Web.Http.Hosting; | |
using System.Web.Http.OData; | |
using System.Web.Http.OData.Builder; | |
using Microsoft.Data.Edm; | |
namespace NewSoTests | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); | |
builder.EntitySet<Customer>("Customers"); | |
IEdmModel model = builder.GetEdmModel(); | |
HttpServer server = new HttpServer(); | |
server.Configuration.MessageHandlers.Add(new DollarFormatHandler()); | |
server.Configuration.Routes.MapODataRoute("default", "", model); | |
HttpClient client = new HttpClient(server); | |
var response = client.GetAsync("http://localhost/Customers?$format=application/json;odata=fullmetadata").Result; | |
Console.WriteLine(response.Content.ReadAsStringAsync().Result); | |
response.EnsureSuccessStatusCode(); | |
Console.ReadKey(); | |
} | |
} | |
public class DollarFormatHandler : DelegatingHandler | |
{ | |
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
var queryParams = request.GetQueryNameValuePairs(); | |
var dollarFormat = queryParams.Where(kvp => kvp.Key == "$format").Select(kvp => kvp.Value).FirstOrDefault(); | |
if (dollarFormat != null) | |
{ | |
request.Headers.Accept.Clear(); | |
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(dollarFormat)); | |
// remove $format from the request. | |
request.Properties[HttpPropertyKeys.RequestQueryNameValuePairsKey] = queryParams.Where(kvp => kvp.Key != "$format"); | |
} | |
return base.SendAsync(request, cancellationToken); | |
} | |
} | |
public class Customer | |
{ | |
public int ID { get; set; } | |
public string Name { get; set; } | |
} | |
public class CustomersController : ODataController | |
{ | |
[Queryable] | |
public IEnumerable<Customer> GetCustomers() | |
{ | |
return new[] { new Customer() }; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment