Json Hijacking Restsharp. modify response content before deserialization. - c#

Ok. So I'm trying to use Restsharp as a Http Client.
Basicaly I need to modify a response content before deserialization.
Is there a point of extension where I could do this?
You know what I mean?
Form API I, get valid json answer but with ")]}',"( hijacking prevention) as a prefix.
Now I need to remove it.
Is there a way to do that?

Weel I think I figure it out.
I have to execute result first and then Deserializer class that i have derived from JsonDeserializer;
var reult = client.Execute(request);
var u = new MyDeserializer().Deserialize<UserGuamInformations>(reult);
and part of the class:
public new T Deserialize<T>(IRestResponse response){
string str = response.Content;
response.Content = str.Remove(0, 6);//remove )]}',\n
return base.Deserialize<T>(response);
}

Related

What is the idiomatic way to make a get request using RestSharp?

I'm trying to make a GET request to a REST api which returns a JSON. This is what I have right now:
RestClient client = new RestClient(BASE_URL);
var request = new RestRequest(CONTROLLER_PATH);
var response = await client.GetAsync<MyDtoClass[]>(request);
When this code executes, response is an array of MyDtoClass but the fields in each element of the array are null. If instead, I run this code (I removed the generic):
RestClient client = new RestClient(BASE_URL);
var request = new RestRequest(CONTROLLER_PATH);
var response = await client.GetAsync(request);
then response is a string represintation of the JSON that BASE_URL + CONTROLLER_PATH returns (nothing is null).
What is the idiomatic way to make a request to this REST api and convert the response into an array of MyDtoClass. Also, if anyone has suggestions for a library you think is better then RestSharp, please share.
Thank you in advance.
The issue was that MyDtoClass had fields instead of properties.

Unable to deserialize JSON in C# using the same class at both ends

I'm looking for someone to point out the obvious blunder here.
A .NET Core in C# application makes an HTTP call to another such application. Some processing is performed, and a response is sent thus:
Response response = new Response(input)
{
stuff = processedStuff;
};
responseMessage = JsonConvert.SerializeObject(response);
return new OkObjectResult(responseMessage);
This all looks good and responseMessage contains valid JSON (according to an online JSON checker I found).
At the other end, this is received thus:
Response returned = new Response();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
returned = JsonConvert.DeserializeObject<Response>(json);
}
This fails with an Error converting value *the JSON string* to "Response" at line 1
Response is the same class file in both applications. What never obvious and apparently invisible mistake am I making here?
The invisible mistake you are making is double-serializing the result. The contract of OkObjectResult is that it will automatically serialize the result object to the negotiated content type (e.g. JSON or XML) and return an OK status. You are serializing the object first and then passing the serialized string to OkObjectResult so it ends up getting serialized twice.
responseMessage = JsonConvert.SerializeObject(response); // serialize to JSON
return new OkObjectResult(responseMessage); // implicit serialization here
Possible solutions:
Allow the implicit serialization to do its thing (recommended):
return new OkObjectResult(response); // implicit serialization of response object
Use a ContentResult instead (good if you need special serialization handling):
responseMessage = JsonConvert.SerializeObject(response); // serialize to JSON
return new ContentResult()
{
Content = responseMessage,
ContentType = "application/json",
StatusCode = 200
};
Deserialize twice on the receiving end (use as a last resort, i.e. you don't control the server):
var doubleSerializedJson = await response.Content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<string>(doubleSerializedJson);
returned = JsonConvert.DeserializeObject<Response>(json);
check if the returned string is not wrapped in OkObjectResult object.
As far as I know, you don't need the serialization and deserialization, the framework already takes care of everything. If you need to, you could always deserialize to either an anonymous type or cast it from object.
https://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm
I would also help if you could share the response class, since it's most likely part of the problem.
As someone old enough to remember when the Simpsons started, I can only answer in the traditional manner:
D'oh!
Using implicit serialization as described by the kind responder above resolved the issue.

How to get response data from RestSharp to download for user?

I am using RestSharp to call an HTTP service via a Querystring. The service generates a Word document.
When I call this service, it looks like a Word document is being returned in the "Content" property, but I struggling to work out how to return this content to the user via the traditional download window as a word document for saving.
public ActionResult DocGen(string strReportId)
{
var client = new RestClient("http://localhost:88");
var request = new RestRequest("DocGen/{id}", Method.GET);
request.AddUrlSegment("id", "1060"); // replaces matching token in request.Resource
// execute the request
//RestResponse response = (RestResponse) client.Execute(request);
IRestResponse response = client.Execute(request);
if (response.ErrorException != null)
{
const string message = "Error retrieving response. Check inner details for more info.";
var myException = new ApplicationException(message, response.ErrorException);
throw myException;
}
// Important and simple line. response.rawbytes was what I was missing.
return File(response.RawBytes,response.ContentType,"sample.doc");
}
Should this be an action?
The content type seems correct ie Word.11
So how do I code get this Response.Content back to the user?
Many thanks in advance.
EDIT
I was closer to the solution than I thought. Power to RestSharp I guess !! See above. Now there might be a better way, and I am all ears for any suggestions, but this is where I am at at present.
return File(response.RawBytes,response.ContentType,"sample.doc");
In case anyone may benefit.

HttpResponseMessage.Content.ReadAsStringAsync don't deserialize JSON when it come from CreateErrorResponse

if i return from my selfhosted webapi
Request.CreateResponse(HttpStatusCode.OK, "YAY");
everything is fine.. so i can read it like that:
var responseStr = await Client.Content.ReadAsAsync<string>();
and then make something like "MessageBox.Show(responseStr);
if i return
Request.CreateErrorResponse(HttpStatusCode.NotFound, "something went wrong!");
and i read it out the same way or even with(doesn't matter how):
Client.Content.ReadAsStringAsync();
the string is not deserialized and i get an error when trying to parse / read as string.
if i read it as object .. it's fine.. but i can't perform object.ToString();
i get errors..
why? and how to fix it?
I found that there were extra '\' and '"' in the returned JSON.
So before I serialize back to an object, I needed to remove the extra chars.
e.g.
string jsonString = httpResponseMessage.Content.ReadAsStringAsync()
.Result
.Replace("\\", "")
.Trim(new char[1] { '"' });
List<VwAisItemMaster> vwAisItemMasterList = JsonConvert.DeserializeObject<List<VwAisItemMaster>>(jsonString);
The better solution is just to fix the issue when creating the response in the webapi method.
Note the type in the CreateResponse method.
IList<VwItemMaster> vwItemMasterList = this.itemMastersGetByUpc(unitOfWork, upc);
HttpResponseMessage httpResponseMessage = this.Request.CreateResponse<IList<VwItemMaster>>(HttpStatusCode.OK, vwItemMasterList);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

Content of HttpResponseMessage as JSON

I have an ASP.NET MVC WEB API. For several reasons (redirect because of no authorizations ..), I can't just use a simple object and return it in my controller method. Therefore I need the HttpResponseMessage class which allows me to redirect.
Currently I'm doing this:
var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound };
var formatter = new JsonMediaTypeFormatter();
response.Content = new ObjectContent<Response>(response, formatter, "application/json");
.. to get the object, serialized as JSON, into the content of HttpResponseMessage. Somehow, I have the feeling that there is another, better, way to do this. Any ideas on that?
You can do:
var response = new Response { responseCode = Response.ResponseCodes.ItemNotFound };
Request.CreateResponse<Response>(HttpStatusCode.OK, response);
By default, Web API will set the format of the response based on the Content-Type specified in the HTTP request header but there are some overloads on the CreateResponse method where you can specify the type formatter.
You can also remove the Web API XML serializer to force all responses to be JSON if that's what you want - off the top of my head I think it's a Formatters.Remove method on HttpConfiguration.

Categories

Resources