Error The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8' while executing webapi - asp.net-web-api

I am getting a runtime time error while executing the following web api method
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
web api controller
[Route("api/movies")]
public IHttpActionResult Get()
{
var movies = _movieBusiness.GetAllMovies();
return Ok(movies);
}
Business logic method
public List<Movie> GetAllMovies()
{
var movies = _movieRepository.GetMovies();
_unitOfWork.Dispose();
return movies;
}
Data access method
public List<Movie> GetMovies()
{
var query = "dbo.spGetMovies";
var list = SqlMapper.Query<Movie>(_unitOfWork.GetConnection(), query, commandType: CommandType.StoredProcedure);
return list;
}

The issue has been fixed. The reason is the assembly in the DTO project had an outdated Newtonsoft.json dll. Updating the DLL worked for me.

Related

Posting to WebAPI with ModelClass Object as Parameter

We have web api like below:
[HttpPost]
public CustomAuthenticateModel AuthenticateByUsername(LoginModel model)
{
return employeeService.AuthenticateByUsername(model.Username, model.AdDomain, model.IsAdAuthentication);
}
In my PCL Project I am trying to access via:
try
{
HttpResponseMessage response = null;
LoginModel l = new LoginModel();
l.Username = model.Email;
response = await apiClient.PostAsJsonAsync(uri, l); // Exception is fired at this line
}
catch(exception etc){}
and every time I am getting exception like:
ex = {System.TypeInitializationException: The type initializer for 'System.Net.Http.FormattingUtilities' threw an exception. ---> System.NotImplementedException: The method or operation is not implemented.
at System.Runtime.Serialization.XsdDataContractExporte...
This is an existing project, all API consume Model Class object as parameter. what is the right way to do this? I am trying to use MVVM helper library for this project.
Serialize your object before making a request. Javascript Serializer should work as good as Newtonsoft serializer
var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(argument);
var content = new StringContent(jsonRequest, Encoding.UTF8, "text/json");
//url is the api, l is your object that you are passing
var response = await client.PostAsync(url, l);
if (response.IsSuccessStatusCode)
{
//R is your object type, in this case LoginModel
result = Newtonsoft.Json.JsonConvert.DeserializeObject<R>(await response.Content.ReadAsStringAsync());
}

Update data with Microsoft.AspNet.WebApi

Hey i am having a big trouble updating data in my client side REST application.
I made a Web API controller.
// PUT: api/Contacts/5
[ResponseType(typeof(void))]
public IHttpActionResult PutContact(Contact contact, int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != contact.ContactId)
{
return BadRequest();
}
_contactService.Update(contact);
return StatusCode(HttpStatusCode.NoContent);
}
And also client side service method:
public async Task<T> PutData<T>(T data, int dataId)
{
HttpResponseMessage resp = await this._client.PutAsJsonAsync(_serviceUrl + "/" + dataId, data);
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadAsAsync<T>();
}
Service URL shows in debug mode that i goes to endpoint:
http://localhost:21855/api/Contacts/8
But it does not even go to breakpoint when i debug my server controller PutContact method.
What i am doint wrong? I need to update the data but i cant, because my client-side application won't even go to servers breakpoint on debug mode!!!
It gives me an error response 405 : Method not allowed
You can't have two different body parameters in the same method.
What you need to do is to set the id parameter to come from the URI and the Contact parameter from the body, like this:
public IHttpActionResult PutContact([FromBody]Contact contact, [FromUri]int id)
{
// method code
}
BTW, I suppose you have a GET method in your controller which looks like this:
public IHttpActionResult GetContact(int id)
{
// method code
return Contact; // pseudo-code
}
The error you getting comes from the fact that the system is not really calling your PUT method but the GET one (the system is ignoring the Contact parameter for the reason I expressed before): calling a GET method with a PUT verb results in a 405 Method Not Allowed exception.

How do I download a file from a Byte[] array in a Web Api2 method that returns IHttpActionResult?

Below is the method I've got in my ApiController class.
The _fileContents dictionary is populated in another WebApi2 method BuildContent(params).
When the user makes an ajax call to the BuildContent(params) method, the method builds
the string end of the dictionary, which contains full HTML content including a table tag and passes back a the Guid, end of the dictionary. The javascript in turn does the following:
window.location = 'api/MyController/DownloadFile/' + guid;
ApiController static:
private static Dictionary<Guid, String> _fileContents = new Dictionary<Guid, String>();
ApiController method:
public IHttpActionResult DownloadFile(Guid guid)
{
try
{
if (_fileContents.ContainsKey(guid))
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var content = Encoding.ASCII.GetBytes(_fileContents[guid]);
using (var stream = new MemoryStream(content))
{
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "MyFile.bin";
}
return Ok(result);
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
return BadRequest();
}
The calling sequence works perfectly but the DownloadFile() method throws the following exception:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Net.Http.StreamContent' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.InvalidDataContractException
</ExceptionType>
Can anyone tell me what is going on and how to accomplish my goal of downloading a simple html file?

Breeze API Controller - The 'ObjectContent`1' type failed to serialize the response body for content type

I am getting this error when attempting to call the
public object Lookups() {
var divisions = _contextProvider.Context.Divisions;
return divisions;
}
on the Breeze API controller.
The ObjectContent`1' type failed to serialize the response body for content type
What I'm I doing wrong ?
Return an object, not an IQueryable.
public object Lookups() {
var divisions = _contextProvider.Context.Divisions;
return new { divisions };
}

Post Scalar data type using HttpClient.PostAsJsonAsync

I am invoking ASP .Net Web API using HttpClient and invoke actions successfully. Also I am able to POST custom object into action as well.
Now problem I am facing is, not able to post scalar data type like Integer,String etc...
Below is my controller and application code that invokes action
// Test application that invoke
[Test]
public void RemoveCategory()
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage();
HttpResponseMessage response = client.PostAsJsonAsync<string>("http://localhost:49931/api/Supplier/RemoveCategory/", "9").Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
// Controller and Action in Web API
public class SupplierController : ApiController
{
NorthwindEntities context = new NorthwindEntities();
[HttpPost]
public HttpResponseMessage RemoveCategory(string CategoryID)
{
try
{
int CatId= Convert.ToInt32(CategoryID);
var category = context.Categories.Where(c => c.CategoryID == CatId).FirstOrDefault();
if (category != null)
{
context.Categories.DeleteObject(category);
context.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Delete successfully CategoryID = " + CategoryID);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Invalid CategoryID");
}
}
catch (Exception _Exception)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, _Exception.Message);
}
}
When I Post custome object that represent "Category" table in Northwind database all things working properly but I am not able to post scalar data like Integer and String
When I am post string data type I am getting following exception
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:49931/api/Supplier/RemoveCategory/'.","MessageDetail":"No action was found on the controller 'Supplier' that matches the request."}
Can anyone guide me?
You will have to mark your CategoryID parameter as [FromBody]:
[HttpPost]
public HttpResponseMessage RemoveCategory([FromBody] string CategoryID)
{ ... }
By default, simple types such as string will be model bound from the URI.

Resources