我写了一个简单的Web API ver 2 - ODATA服务器。建模是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; }
}
}
然而,当我发送POST请求时,我得到异常
POST odata / Clients HTTP / 1.1 Content-ID:1 DataServiceVersion:2.0 接受: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
{ “客户端ID”: - 1, “姓”:NULL, “名字”:NULL, “TID”:NULL, “电话1”:NULL, “电话2”:NULL, “住址”:NULL, “DrivingSchoolName”日期null}
我收到错误
{ “odata.error”:{ “代码”: “”, “消息”:{ “lang”:“en-US”,“value”:“此资源不支持请求实体的媒体类型'application / json'。” }, “innererror”:{ “message”:“没有MediaTypeFormatter可用于从媒体类型为'application / json'的内容中读取'Client'类型的对象。”,“type”:“System.Net.Http.UnsupportedMediaTypeException”,“stacktrace”:“在System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型类型,IEnumerable
1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable
1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)\ r \ n在System.Web.Http.ModelBinding.FormatterParameterBinding。 ReadContentAsync(HttpRequestMessage请求,类型类型,IEnumerable`1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)“ } } }
我的控制器派生自ODATAController,我有POST动作
public async Task<IHttpActionResult> Post([FromBody] Client todoitem)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_contextovider.Clients.Add(todoitem);
await _contextovider.SaveChangesAsync();
return Created(todoitem);
}
在检查格式化程序时,JsonMediaFormatter存在
答案 0 :(得分:1)
您必须在Client
中将Application_Start
注册为实体集,作为OData模型的一部分。
例如:
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Client>("Clients");