Wednesday, 5 November 2014

Exception: ASP.NET Web API - No 'MediaTypeFormatter' is available to read an object of type T

Questions: ASP.NET Web API - No 'MediaTypeFormatter' is available to read an object of type T where T is a primitive type or class type.
Scenarios: I've created a WebAPI as follows:

[RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        private AuthRepository _repository;

        public AccountController()
        {
            _repository = new AuthRepository();
        }

        // POST  api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        [HttpPost]
        public async Task<IHttpActionResult> Register(UserModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            IdentityResult result = await _repository.RegisterUser(model);
            IHttpActionResult errorResult = GetErrorResult(result);
            if (errorResult != null)
            {
                return errorResult;
            }
            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _repository.Dispose();
            }
            base.Dispose(disposing);
        }
        #region Private Methods
        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }
            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
                if (ModelState.IsValid)
                {
                    return BadRequest();
                }
                return BadRequest(ModelState);
            }
            return null;
        }
        #endregion

    }
Now I calling this API register method through the POSTMAN Extension like as follows:
But I'm getting "ASP.NET Web API - No 'MediaTypeFormatter' is available to read an object of type T where T is a primitive type or class type" error. Please suggest me where am I doing wrong.

Answer/Solutions: Actually 'MediaTypeFormatter' is responsible for this exception when you didn't included media type in Request Header. So to fix the problem just add MediaType in header like this way.
{
content-type: "application/json"
}
or in case of POSTMAN extension you can add as follows:

I hope it might be helpful. Please feel free comment for any suggestion.

No comments:

Post a Comment