内容协商在Web Api中不起作用

时间:2016-02-01 12:13:27

标签: c# asp.net asp.net-web-api2

我有以下代码来演示web api中的内容协商。但它会抛出异常。

IEnumerable<Person> personList = _repository.GetAllPerson();

if (personList == null)
    throw new HttpResponseException(HttpStatusCode.NotFound);

IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();
ContentNegotiationResult result = negotiator.Negotiate(typeof(Person), this.Request, this.Configuration.Formatters);
if (result == null)
{
    var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
    throw new HttpResponseException(response);
}

HttpResponseMessage responseMsg = new HttpResponseMessage()
{                
    Content = new ObjectContent<IEnumerable<Person>>(
        personList, // What we are serializing 
        result.Formatter, // The media formatter
        result.MediaType.MediaType // The MIME type
        )
};

return Request.CreateResponse(HttpStatusCode.OK, responseMsg);

例外是:

  

'ObjectContent`1'类型无法序列化响应正文   内容类型'application / json;字符集= UTF-8' 。

请给我一个建议。我的WebApiConfig.cs代码是:

// Web API configuration and services

//XML output
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
xml.UseXmlSerializer = true;

//Json output
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;
json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;

// Remove the XML formatter
//config.Formatters.Remove(config.Formatters.XmlFormatter);

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

2 个答案:

答案 0 :(得分:1)

这是关于序列化,而不是内容协商。我猜你是在查询数据库并使用Entity Framework从存储库中获取IQueryable结果?尝试几个步骤:

改变这个:

json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;

到此:

json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Ignore;

您可能还需要在EF配置中禁用延迟加载,具体取决于Person的形状:

public MyEntitiesContext() : base("name=MyEntitiesContext", "MyEntitiesContext")
{
    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;
}

另一种选择(对于一个非平凡的解决方案而言,可能更好的策略是从web api返回不同的类(视图模型,dto或甚至投影),而不是返回您的EF实体。

答案 1 :(得分:1)

问题在于最后一行。

return Request.CreateResponse(HttpStatusCode.OK, responseMsg);

答案是:

return new HttpResponseMessage()
            {
                Content = new ObjectContent<IList<PersonModel>>(
                    personModelList, // What we are serializing 
                    result.Formatter, // The media formatter
                    result.MediaType.MediaType // The MIME type
                    ),
                StatusCode = HttpStatusCode.OK
            };