Return camelCased JSON from Web API

前端 未结 6 1102
攒了一身酷
攒了一身酷 2020-12-31 11:42

I\'m trying to return camel cased JSON from an ASP.Net Web API 2 controller. I created a new web application with just the ASP.Net MVC and Web API bits in it. I hijacked t

6条回答
  •  旧时难觅i
    2020-12-31 12:06

    Looks like the main issue was that I was using the JsonResult shortcut Json() action result method:

    public IHttpActionResult Get([FromUri] string domain, [FromUri] string username)
    {
        var authInfo = BLL.GetAuthenticationInfo(domain, username);
        return Json(authInfo);
    }
    

    It apparently had full control of formatting the results. If I switch to returning HttpResponseMessage then it works as expected:

    public HttpResponseMessage Get([FromUri] string domain, [FromUri] string username)
    {
        var authInfo = BLL.GetAuthenticationInfo(domain, username);
        return Request.CreateResponse(HttpStatusCode.OK, authInfo);
    }
    

    I did end up using the block of code in the WebApiConfig file as Omar.Alani suggested (opposed to the much lengthier code I had in my OP). But the real culprit was the JsonResult action method. I hope this helps someone else out.

提交回复
热议问题