【发布时间】:2025-12-27 03:40:12
【问题描述】:
我有以下代码来演示 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”类型未能序列化响应正文 内容类型'应用程序/json; charset=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 }
);
【问题讨论】:
标签: c# asp.net asp.net-web-api2