1
votes

I have wrote a simple Web API ver 2 - ODATA server. the modeling is EF6

public class Client
{
    private ICollection<ClientCar> _cars; 
    public Client()
    {
        _cars = new List<ClientCar>(); 
    }

    [Key]
    public int ClientID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string TID { get; set; }
    public string Phone1 { get; set; }
    public string Phone2 { get; set; }
    public string Adress { get; set; }
    public string DrivingSchoolName { get; set; }

    public virtual ICollection<ClientCar> Cars
    {
        get { return _cars; }
        set { _cars = value; }
    }

}

however when I send POST request i get exception

POST odata/Clients HTTP/1.1 Content-ID: 1 DataServiceVersion: 2.0 Accept: application/atomsvc+xml;q=0.8, application/json;odata=fullmetadata;q=0.7, application/json;q=0.5, /;q=0.1 Content-Type: application/json MaxDataServiceVersion: 3.0

{"ClientID":-1,"FirstName":null,"LastName":null,"TID":null,"Phone1":null,"Phone2":null,"Adress":null,"DrivingSchoolName":null}

I get error

{ "odata.error":{ "code":"","message":{ "lang":"en-US","value":"The request entity's media type 'application/json' is not supported for this resource." },"innererror":{ "message":"No MediaTypeFormatter is available to read an object of type 'Client' from content with media type 'application/json'.","type":"System.Net.Http.UnsupportedMediaTypeException","stacktrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" } } }

My controller derives from ODATAController and I have POST action

 public async Task<IHttpActionResult> Post([FromBody] Client todoitem)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _contextovider.Clients.Add(todoitem);
        await _contextovider.SaveChangesAsync();

        return Created(todoitem);
    }

And when inspecting the formatters the JsonMediaFormatter exists

1
However I can't reproduce your issue. Can you provide with more details? A repro project would be great. - Feng Zhao

1 Answers

1
votes

You have to register Client as an entity set as part of the OData model in Application_Start.

For example:

ODataModelBuilder builder = new ODataConventionModelBuilder();

builder.EntitySet<Client>("Clients");