RestSharp Serializer Setter has no effect - asp.net-mvc

I am struggling to make RestSharp talk with MVC API with EF4 and I'm very close to making it work. In order to overcome the interface limitation of the stock serializer I am using the Json.NET serializer. For the deserialization it worked out of the box but I can't make RestSharp use my custom serializer. The method Serializeis not getting called. Everything compiled great but doesn't work. Here is the code:
var client = CreateClient();
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("api/{type}s", Method.GET);
request.AddUrlSegment("type", typeof(T).Name);
request.RequestFormat = DataFormat.Json;
request.AddParameter("criteria", criteria);
IRestResponse<List<T>> response = client.Execute<List<T>>(request);
HandleResponse(response);
return response.Data;
Any ideas?
Edit
I tried to follow an example and change the post method to accept JObject and it worked!. But trying to call jitem.ToObject<Item>() caused the following exception:
Error converting value "System.Collections.Generic.List`1[DataAbstractionLayer.Poco.ItemCheckpoint]" to type 'System.Collections.Generic.ICollection`1[DataAbstractionLayer.Poco.ItemCheckpoint]'.
But more interesting is the inner exception:
Could not cast or convert from System.String to System.Collections.Generic.ICollection`1[DataAbstractionLayer.Poco.ItemCheckpoint].
Could it be that Json.NET converts collection items automatically to string?

Related

What is the alternative for jsonp format in MVC core?

I need to return result in jsonp format while I'm using asp.net MVC Core.
In asp.net MVC we can use MVC.jsonp dll an it's work fine but what is the alternative in MVC Core because I can't find any.
public JsonpResult FunctionalitesTblList()
{
var settings = new JsonSerializerSettings();
return Jsonp(Rows, settings);
}
There was no built in ability to handle JSONP with MVC, so you were always using a third-party addition. Apparently, that library is incompatible with .NET Core. Therefore, your option is to find a similar library that is compatible or choose some other approach.
#CuongLe is correct that CORS is a better approach overall, so you should definitely investigate that. However, if you insist on JSONP, it's so simple to implement manually, you don't really need a library.
Simply, all JSONP is a is JSON passed into a "callback" function, specified by the client. In other words, if the callack was specified as "mycallback", the response should just look like:
mycallback({ "foo": "bar" });
As a result, your code simply becomes:
string json = null;
using (var ms = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(typeof(Foo));
serializer.WriteObject(ms, foo);
json = Encoding.UTF8.GetString(ms.ToArray());
}
var jsonp = String.Format("{0}({1});", callback, json);
Response.ContentType = "application/javascript";
return Content(jsonp);

Dynamic binding model for use in HttpClient

I have a Web Api that takes a complex object and adds it to the database.
var myWidgit= new Widgit() {
Name = "WidgitName",
Price = 50,
Category = "Appliance" };
HttpResponseMessage response = client.PostAsync("api/createwidgit", myWidgit);
I need to make a one off call to the API and I would like to avoid creating a separate class file for Widgit.
Is there a way to define the Widgit class and assign it values in the method that makes use of it? Sort of like a dynamic class just used in this method.
I think I figured it out ...
HttpResponseMessage response = client.PostAsync("api/createwidgit", new StringContent(string.Format("Name={0}&Price={1}&Category={2}", HttpUtility.UrlEncode("WidgitName"), HttpUtility.UrlEncode(50), HttpUtility.UrlEncode("Appliance"), Encoding.UTF8, "application/x-www-form-urlencoded"));
Essentially the dynamic object I was looking to create is accomplished using
new StringContent(string.Format("Name={0}&Price={1}&Category={2}", HttpUtility.UrlEncode("WidgitName"), HttpUtility.UrlEncode(50)), HttpUtility.UrlEncode("Appliance"), Encoding.UTF8,
"application/x-www-form-urlencoded")
Sorry I could not figure out better formatting

SingleResult<T> not serializable in Web API when querying by key

Trying to find single record using primary key CourseID against odata web.api using this:
var editedcourse = container.Courses.Where(c => c.CourseID == ID).SingleOrDefault();
This is error:
<m:innererror>
<m:message>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/atom+xml; charset=utf-8'.</m:message>
<m:type>System.InvalidOperationException</m:type>
<m:stacktrace></m:stacktrace>
<m:internalexception>
<m:message>'SingleResult`1' cannot be serialized using the ODataMediaTypeFormatter.</m:message>
<m:type>System.Runtime.Serialization.SerializationException</m:type>
The web.api controller method by default was not queriable, thus client failed. Added annotation to fix: [Queryable(AllowedOrderByProperties = "Id")]
Try adding the code below to your WebApiConfig.cs file.
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
I think the first two lines are optional if you don't use Json format.
Refer to
http://social.msdn.microsoft.com/Forums/vstudio/en-US/a5adf07b-e622-4a12-872d-40c753417645/web-api-error-the-objectcontent1-type-failed-to-serialize-the-response-body-for-content?forum=wcf
I think you have to make sure any relations are loaded. As a workaround you could create a new DTO (data transfer object) and put all you need in it.

Using the Json.NET serializer in an MVC4 project

I'm starting to learn Json.NET, but I'm having trouble using its serializer. I have a new MVC4 project with a Web.API service:
public class PTE_TestsController : ApiController {
PTE_TestsRepository _repository = new PTE_TestsRepository();
// GET /api/PTE_Tests/5
public HttpResponseMessage<string> Get(int id) {
try {
PTE_Test test = _repository.GetTest(id);
return new HttpResponseMessage<string>(JsonConvert.SerializeObject(test));
} catch {
return new HttpResponseMessage<string>(HttpStatusCode.NotFound);
}
}
}
JsonConvert.SerializeObject() works as expected and returns a string. My Web.API controller returns that as part of an HttpResponseMessage. The end result, when viewed in Fiddler, is not JSON data, but JSON data being serialized again (I think):
"{\"ID\":1,\"Name\":\"Talar Tilt\",\"TagID\":1,\"PracticeID\":1,
\"SpecificAreaID\":1,\"TypeID\":1,\"VideoID\":1,\"PicID\":1}"
Does someone know how to turn off the default serializer so I can use Json.NET directly? By the way, I'm not using the default serializer because I can't figure out how to make it work with complex objects (PTE_Test will eventually contain members of type List).
Alternately, it will also solve my problem if someone can explain how to use the default serializer with complex objects. MSDN's explanation didn't help me.
Rick Strahl has a blog on that here with a code that works.
As others have pointed out, you need to create a formatter and replace the DataContractSerializer with the JSON.NET serializer. Although, if you're not in a rush for JSON.NET specifically, rumor has it that next beta/rc is going to have support for JSON.NET built in.
Conceptually, however, you're missing part of the magic of WebAPI. With WebAPI you return your object in it's native state (or IQueryable if you want OData support). After your function call finishes the Formatter's take over and convert it into the proper shape based on the client request.
So in your original code, you converted PTE_Test into a JSON string and returned it, at which point the JSON Formatter kicked in and serialized the string. I modified your code as follows:
public class PTE_TestsController : ApiController {
PTE_TestsRepository _repository = new PTE_TestsRepository();
public HttpResponseMessage<PTE_Test> Get(int id) {
try {
PTE_Test test = _repository.GetTest(id);
return new HttpResponseMessage(test);
} catch {
return new HttpResponseMessage<string>(HttpStatusCode.NotFound);
}
}
}
Notice how your function returns PTE_Test instead of string. Assuming the request came in with a request header of Accept = application/json then the JSON formatter will be invoked. If the request had a header of : Accept = text/xml the XML formatter is invoked.
There's a decent article on the topic here. If you're a visual learner, Scott Gu shows some examples using fiddler in this video, starting around 37 minutes. Pedro Reys digs a little deeper into content negotiation here.
The way to do this is to use formatters.
Check out: https://github.com/WebApiContrib/WebAPIContrib/tree/master/src/WebApiContrib.Formatting.JsonNet.
Json.NET support will be in the RC release of Web API.

ASP.NET 4.0 JSON from WebService - Removing Escape Slashes

Hi I'm hitting my head against the wall here...
I'm using DataContractJsonSerializer to encode data that I'm retrieving from the database which I'm sending back to an AJAX call...
I have this extension:
public static string ToJSON<T>(this T obj) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, obj);
return Encoding.Default.GetString(stream.ToArray());
}
}
and I'm calling it from the ASMX:
return _webServiceService.GetSponsors().ToJSON();
Passing in the resultset from a Stored Procedure using Entity Framework
It's all work kinda working, except this is part of what's being returned:
{"d":"[{\"FileID\":296,\"IconUrl\":\"\\/Files\\/Banners\\/20119\\/00B56BAC.jpg\",\"ImageUrl\":....
How on earth to I get rid of the slashes so that it returns the following:
{"d":"[{"FileID":296,"IconUrl":"/Files/Banners/20119/00B56BAC.jpg","ImageUrl":....
I'm trying to implement the JQuery UI Autocomplete. Well I'm guessing this will sort it, not sure if I need the FileID value within quotes?
You don't need to JSON serialize the return value by hand, because ASP.NET will handle it for you automatically in that scenario. What you're seeing there is ASP.NET applying a second level of JSON serialization to your manually generated string, which requires escaping double quotes with backslashes.
Change your ASMX method to return something like List<Sponsor> and return _webServiceService.GetSponsors() directly, without the ToJSON() extension.

Resources