Global Json Formatting not working

1.2k Views Asked by At

I have a problem with my json formatting. I want that my json result is in camel case. I use the following code to achieve this (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();
    }
}

The Register method is called from the 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();
    }
}

But when i call the following method in my browser:

[HttpGet]
public JsonResult GetUser()
{
    var user = ESP.Framework.Web.Security.UserManager.GetAllUser();

    return Json(user, JsonRequestBehavior.AllowGet);
}

The result is not in camel case (The assembly in which the method is, is dynamically loaded).

Maybe someone has an solution. Thank you!

2

There are 2 best solutions below

1
On BEST ANSWER

I think you are mixed mvc website and WebApi,In asp.net current version, they use different api. You set the WebApi config, but use the Mvc website's api. You should use WebApi version:

using System.Web.Http;

public class UserController : ApiController
{
    [Route("user/getalluser")]
    public IEnumerable<User> Get()
    {
        return GetAllUser();
    }
}

Then you can access url 'user/getalluser' to get json data

0
On

Ok, i found a solution:

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);
}

But it is not very nice...