我的json格式有问题。我希望我的json结果是在驼峰的情况下。我使用以下代码来实现此目的(ASP.NET WebAPI Tip #3: camelCasing JSON):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var formatters = config.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Newtonsoft.Json.Formatting.Indented;
settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}
从Global.asax
:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Load all modules
ESP.Framework.Web.ModuleManager.Singleton.LoadModules(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath);
// Virtual Path Provider
// // System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(new Provider.ESPPathProvider());
// Register Controller-Factory
//ControllerBuilder.Current.SetControllerFactory(typeof(ESP.Web.Controllers.DynamicActionControllerFactory));
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
但是当我在浏览器中调用以下方法时:
[HttpGet]
public JsonResult GetUser()
{
var user = ESP.Framework.Web.Security.UserManager.GetAllUser();
return Json(user, JsonRequestBehavior.AllowGet);
}
结果不是在camel情况下(方法所在的程序集是动态加载的)。
也许有人有解决方案。谢谢!
答案 0 :(得分:1)
我认为你是混合mvc网站和WebApi,在asp.net当前版本中,他们使用不同的api。您设置WebApi配置,但使用Mvc网站的api。您应该使用WebApi版本:
using System.Web.Http;
public class UserController : ApiController
{
[Route("user/getalluser")]
public IEnumerable<User> Get()
{
return GetAllUser();
}
}
然后您就可以访问网址&#39; user / getalluser&#39;获取json数据
答案 1 :(得分:0)
好的,我找到了一个解决方案:
public string SerializeObject(object toSerialize)
{
var settings = new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented };
return JsonConvert.SerializeObject(toSerialize, Formatting.None, settings);
}
[HttpGet]
public string GetUser()
{
var user = Simplic.Framework.Web.Security.UserManager.GetAllUser();
return SerializeObject(user);
}
但它不是很好......