Search code examples
serializationasp.net-web-apiasp.net-identity

IdentityUser not serializing Web Api


Not sure what is going on here.

I am exposing the Identity functionality through a Web API project. The CRUD aspect will be exposed to an admin app and the login, registration in a public facing app.

Right now I am just trying to return a list of all users in the database through a Web Api controller action. I am getting nothing output to the response, but I do get back data from the service:

        /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [Route("")]
    public async Task<IHttpActionResult> GetAllUsers()
    {
        var model = await _userService.GetAllUsers(); //<---Gets List<AppUser> here?
        return Ok(model);
    }

This action shows nothing on fiddler or Postman?

Any ideas?

   public class AppUser : IdentityUser
   {
        public DateTime Created { get; set; }
   }

Is there something special about the IdentityUser class that prevents it from being serialized?

Here is the web api serialization config:

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        config.Formatters.Add(new JsonFormatter());


    }

    public class JsonFormatter : JsonMediaTypeFormatter
    {
        public JsonFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            this.SerializerSettings.Formatting = Formatting.Indented;
        }

        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }

Solution

  • Found my answer. The IdentityUser class is not really meant to be exposed over an API; lots of sensitive data and all.

    However this is will sit behind a firewall and I do not feel like writing a DTO and mapper just to make this work.

    The answer is explained here

    Basically you just need to override the properties you want exposed and decorate them with a DataMember attribute for serialization.