Breeze API Controller - The 'ObjectContent`1' type failed to serialize the response body for content type - asp.net-web-api

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

Related

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

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.

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

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?

Posting to Web Api parameters are null

I have a jquery method which looks like this:
$.post("/api/amazon/signature", { "policy": policy }, function (data) {
console.log(data);
});
the api method looks like this~:
// POST api/amazon/signature
[HttpPost]
[Route("api/amazon/signature")]
public IHttpActionResult GetSignature([FromBody]string policy)
{
var bKey = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["AWSSecretKey"]);
var hmacSha1 = new HMACSHA1(bKey);
var bPolicy = Encoding.ASCII.GetBytes(policy);
var hash = hmacSha1.ComputeHash(bPolicy);
var encoded = Convert.ToBase64String(hash);
return Ok(encoded);
}
but when I run this code policy is always null!
If I change my method to this:
public class Signature
{
public string Policy { get; set; }
}
// POST api/amazon/signature
[HttpPost]
[Route("api/amazon/signature")]
public IHttpActionResult GetSignature([FromBody]Signature model)
{
var bKey = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["AWSSecretKey"]);
var hmacSha1 = new HMACSHA1(bKey);
var bPolicy = Encoding.ASCII.GetBytes(model.Policy);
var hash = hmacSha1.ComputeHash(bPolicy);
var encoded = Convert.ToBase64String(hash);
return Ok(encoded);
}
and modify my jquery to this:
$.post("/api/amazon/signature", { "Policy": policy }, function (data) {
console.log(data);
});
it works fine....
Can someone tell me why?
ASP.NET Web API binds the request body in its entirety to one parameter (one parameter only and not more). By default, body is bound to a complex type. So, when you change the parameter type to Policy which is a complex type, you don't need to actually specify FromBody. Also binding works correctly now because you are sending JSON Object which looks something like this { "policy": policy }. Web API has no trouble in binding JSON object to your complex type.
When it comes to a simple type, string in your case, you must specify FromBody, since by default Web API binds from URI path and query string. In that case however, you cannot send a JSON Object. Web API is going to bind the entire body to that parameter, which is string. So, the request body must be just a string like this - "ABC123" and not a JSON object. If you send just "ABC123" (including the quotes) in the request body, your string parameter will be populated with ABC123.

ASP.NET MVC 3 Parse JSon object and display data

I have a class
public class ConversionResultModel
{
public string ProcessId { get; set; }
public bool Result { get; set; }
public string Message { get; set; }
}
sending it to view using JSon
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> clientUpload)
{
string destinationPath = "";
JsonResult result = null;
var fileModel = new ConversionResultModel();
fileModel.ProcessId = "4558-95559-554";
fileModel.Result = true;
fileModel.Message = "test.pdf";
result = Json(new { fileModel }, "text/plain");
return result;
}
How to parse such JSon object at client side using JS or jQuery and read values?
I have tried to parse JSon object with code below but get Undefined error in alert
var obj = $.parseJSON(e.response);
alert(e.obj);
I receive JSon object like this
{"fileModel":{"ProcessId":"4558-95559-554","Result":true,"Message":null,"SourceFile":null,"ConvertedFileName":"test.pdf","ConvertedFileSize":1233444,"DownloadUrl":"http://localhost:2008/download?path=4558-95559-554","DeleteUrl":"http://localhost:2008/download?path=4558-95559-554"}}
You do not need to parse it. Just set data type to JSON during ajax request and then use received data object like entity and you easily can access to any property:
var id = data.ProcessId;
Anyway, using jQuery you can parse JSON string:
var data = jQuery.parseJSON(stringData);
P.S:
Use the following code sample for converting object to JSON in ASP.NET MVC:
return this.Json(fileModel);
http://api.jquery.com/jQuery.parseJSON/
In your case, I think you're getting back the correct JSON, but your alert is looking at the wrong object. Try alert(obj.SomeProperty) rather than alert(e.obj). e.obj doesn't exist, which is likely why you're getting an "undefined" error. For example, alert(obj.fileModel.ProcessId); should work.

Resources