我正在使用带WebApi的asp.net MVC。在localhost上一切正常,但在appharbor部署的网站上,每次调用webapi控制器时都会遇到异常The 'ObjectContent 1 type failed to serialize the response body for content type 'application/json; charset=utf-8'
。
我的webapi功能是:
public async Task<IHttpActionResult> GetMobileTrends()
{
var ret = (from ad in db.MobileAds
orderby ad.Ad.views
where ad.Ad.AdImages.Count > 0
select new
{
title = ad.Ad.title,
id = ad.Ad.Id,
//other attributes
});
return Ok(ret);
}
要解决此异常问题,我在Application_Start
Global.asax.cs
中向protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
函数添加了两行:
Register
但它没有用。然后,我在WebApiConfig.cs
中的var json = configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
configuration.Formatters.Remove(configuration.Formatters.XmlFormatter);
函数末尾添加了以下行:
self.loadad = function () {
url_address = '/api/Electronic/GetMobileTrends';
$.ajax({
url: url_address,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'GET',
success: function (data) {
var mappedads = $.map(data, function (item) { return new ad(item); });
self.showAds(mappedads);
},
error: function () {
toastr.error("Unable to load data. Please try again", "Error");
}
});
}
它仍然无效。我不想创建模型,因为我正在使用淘汰赛。此外,如果我为每个webapi调用创建模型。将有30到40个模型(每次调用中检索的数据不同)。
有没有办法在不创建模型的情况下解决此异常?
更新 我的问题不重复。 我的ajax功能是:
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
int len;
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void print(const int *v)
{
int i;
int size = len;
if (v != 0) {
for ( i = 0; i < size; i++) {
cout<< v[i] ;
}
cout<<'\n';
}
}
void heappermute(int v[], int n) {
int i;
if (n == 1) {
print(v);
}
else {
for (i = 0; i < n; i++) {
heappermute(v, n-1);
if (n % 2 == 1) {
swap(&v[0], &v[n-1]);
}
else {
swap(&v[i], &v[n-1]);
}
}
}
}
int main()
{
int num[11];
int i;
cout<<"How many numbers you want to enter: ";
cin>>len;
cout<<"\nEnter the numbers: ";
for ( i = 0 ; i < len; i++)
cin>>num[i];
heappermute(num, len);
return 0;
}