Asp.net MVC web api Response.CreateResponse sending odd content - asp.net-mvc

Am currently communicating to a Mobile device using Windows Compact Framework 3.5. The message sent to the device is built is as thus,
HttpResponseMessage result;
var response = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"windows-1252\"?><message type=\"response\"><header><datetime>2013-04-03T09:49:35</datetime><sender version=\"1.1.4.1138\"><userid>Connect Server</userid></sender><commandlist><module>ADMIN</module><command1>VALIDATE</command1></commandlist><result type=\"ok\"/></header></message>");
result = Request.CreateResponse(HttpStatusCode.OK, response);
The device then retrieves the message and then uses
Encoding.UTF8.GetString(responseContent);
After decoding the message is:
<base64Binary xmlns="http://schemas.microsoft.com/2003/10/Serialization/">PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0id2luZG93cy0xMjUyIj8+PG1lc3NhZ2UgdHlwZT0icmVzcG9uc2UiPjxoZWFkZXI+PGRhdGV0aW1lPjIwMTMtMDQtMDNUMDk6NDk6MzU8L2RhdGV0aW1lPjxzZW5kZXIgdmVyc2lvbj0iMS4xLjQuMTEzOCI+PHVzZXJpZD5Db25uZWN0IFNlcnZlcjwvdXNlcmlkPjwvc2VuZGVyPjxjb21tYW5kbGlzdD48bW9kdWxlPkFETUlOPC9tb2R1bGU+PGNvbW1hbmQxPlZBTElEQVRFPC9jb21tYW5kMT48L2NvbW1hbmRsaXN0PjxyZXN1bHQgdHlwZT0ib2siLz48L2hlYWRlcj48L21lc3NhZ2U+</base64Binary>
Tried decoding the message on the server before sending it off and it's fine. Unsure what could be going wrong.
Any help would be greatly appreciated.

Request.CreateResponse() uses ObjectContent. For this scenario, you don't want that. You should use either StringContent or StreamContent to return the XML. See this question for details https://stackoverflow.com/a/15372410/6819

You are encoding your XML as binary. You are then returning a byte array. Then your client requests XML in the Accept: application/xml header. The Web API serializes the binary into XML. That's what you're seeing.
Just return the XML as a string and you should have no problems, unless you've tried that already?
See here for similar question.

Related

How do you send MIME format emails using Microsoft Graph Java SDK?

The official documentation does not provide an example for any SDK's (including the Java SDK): https://learn.microsoft.com/en-us/graph/api/user-sendmail?view=graph-rest-1.0&tabs=java#example-4-send-a-new-message-using-mime-format. As there is no example, I have tried in vain to send the MIME content using the SDK (microsoft-graph 5.0.0):
Message sending = new Message();
ItemBody body = new ItemBody();
final String mimeMessageRFC822 = input.getMimeMessageRFC822();
body.content = Base64.getMimeEncoder().encodeToString(mimeMessageRFC822.getBytes());
sending.body = body;
GraphServiceClient service = getService(acHost, configuration);
service
.me()
.sendMail(UserSendMailParameterSet.newBuilder().withMessage(sending).withSaveToSentItems(true).build())
.buildRequest(new HeaderOption("Content-Type", "text/plain"))
.post();
The above code sets the request's content-type to text/plain, however the request body that is being sent is JSON (xxxxxx below is a placeholder for a valid Base64 encoded MIME content string).
{
"message":
{
"body":
{
"content": xxxxxx
}
},
"saveToSentItems": true
}
The response is a 404, stating:
GraphServiceException: Error code: ErrorMimeContentInvalidBase64String
Error message: Invalid base64 string for MIME content.
I can understand why it is responding with this error as the graph endpoint is parsing the text/plain content as base64 encoded MIME but finds the JSON structure instead. I have been on a video call with a Microsoft Graph support agent, and they have seen that my MIME content is valid. Sadly, they are not able to help with the Microsoft Graph Java SDK even though it is developed by Microsoft!
This suggests that we are not supposed to use the Java SDK at all for sending MIME formatted emails. Is this correct? Surely it can't be otherwise what is the point of a library that can receive MIME formatted emails but can't send them? Does anyone have a solution?
For now at least the solution is to send a CustomRequest with MIME content instead of using the fluent API provided by the Graph client.
final String encodedContent = Base64.getMimeEncoder().encodeToString(mimeMessageRFC822.getBytes());
CustomRequest<String> request = new CustomRequest<>(requestUrl, service, List.of(new HeaderOption("Content-Type", "text/plain")), String.class);
request.post(encodedContent);

Change Response Header Encode .Net Core

I need help changing the encoding of the response header on .Net Core 1.1.
We're developing an application and we created a custom header called "X-Application-Error" where any error that happens at the backend of the aplication returns a response code 500 and inside the header the message. This way I use the "app.UseExceptionHandler" to catch the errors, put it inside the header, and the front end, if it recieves and response code 500, displays the message sent at the header.
This is working as expected, the trouble that I'm having is that I need to send chacters like "é", "ã" and others, and the default encoding of the header is UTF-8, so it doesn't display those characters.
At the .net framework, we can use the "HttpResponse.HeaderEncoding" Property to change it (https://msdn.microsoft.com/en-us/library/system.web.httpresponse.headerencoding(v=vs.110).aspx)
but I can't find the equivalent for the .Net Core (1.1)
I found a similar question here (C# WebClient non-english request header value encoding) but no answer too.
Ok, I have found a work around (and yes, it seems obvious to me now).
From what I understood .Net Core won't allow characters like "á", "ã" inside a header if they are not encoded. So I just used "WebUtility.UrlEncode(string)" and sent the message encoded. At the FrontEnd, Angular decoded the message automatically. The code is like:
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
//Some validations I make
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
try
{
context.Response.Headers.Add("Application-Error", WebUtility.UrlEncode(error.Error.Message));
}catch(Exception e)
{
context.Response.Headers.Add("Application-Error", e.Message);
}
//the rest of the code
}
});
});

Support compression in .NET OData 4 Client

Problem
I have added support for http compression in our self-hosted OWIN/Katana Web API OData 4 service but I do not see how to support compression in the .NET client. I'm using OData libraries v6.5.0 and I need to support compression/decompression in the client (OData v4 Client Code Generator). I am using Deflate encoding for the compression via an ActionFilter. Everything compresses correctly on the server as confirmed via Fiddler but I do not know how to configure the client to support this now that the OData client uses the Request and Response Pipelines instead of the now defunct WritingRequest and RecievingResponse events that once supported this very scenario.
Attempts
By experimentation I found that I can hook into the ReceivingResponse event on my DataServiceContext and then call ReceivingResponseEventArgs.ResponseMessage.GetStream() but I don't know what to do to overwrite the message content correctly. If I CopyTo() on the stream, I get a null reference exception at Microsoft.OData.Core.ODataMessageReader.DetectPayloadKind(). I presume this is because the stream was read to the end and the position needs to be set back to zero but I cannot do that because the stream also throws an exception when setting the position back because it says it does not support seeking. I presume this is simply due to the stream being read-only. Even if I could copy the stream to decompress it successfully, how do I modify the response message content with the decompressed content? I don't see any hooks for this at all in the RequestPipeline or ResponsePipeline. To clarify, I want to decompress the response message content and then set it for the materialization that occurs soon after, how might I do that? Extra credit for how to also send compressed requests to the OData service. Thanks!
OData client use the HTTPWebRequest and HTTPWebReponse, which supports the compression well. Try setting the AutomaticDecompression of HTTPWebRequest to Deflate or GZip, in SendingRequest2 pipeline event, like this:
private void OnSendingRequest_(object sender, SendingRequest2EventArgs args)
{
if (!args.IsBatchPart) // The request message is not HttpWebRequestMessage in batch part.
{
HTTPWebRequest request = ((HttpWebRequestMessage)args.RequestMessage).HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
}
Then in response, HTTPWebResponse will decompress the stream automatically, before the materialization work.

Gzip decompress JSON POST body in Rails/Passenger/Nginx

We have a function in our Rails code that accepts a JSON POST body:
contacts = ActiveSupport::JSON.decode(request.raw_post.gsub("+", ""))
(I'm aware that I can get this from params["_json"] as well, but we have extremely large (MBs) POST bodies that do not get put into params["_json"] for some reason (and + throws errors too).
Since the JSON is usually sent from a mobile client, it's important to us to optimize the upload size. We want to switch to having the POST body gzipped.
However, no matter what we do, we get the same error with no line number:
MultiJson::DecodeError (743: unexpected token at ''):
We have tried:
gzipped_contacts = Zlib::GzipReader.new(StringIO.new(request.raw_post)).read
contacts = ActiveSupport::JSON.decode(gzipped_contacts.gsub("+", ""))
This:
gzipped_contacts = ActiveSupport::Gzip.decompress(request.raw_post)
contacts = ActiveSupport::JSON.decode(gzipped_contacts.gsub("+", ""))
And the solution found here: Rails: how to unzip a compressed xml request body?
I'm pretty sure this is not occurring at the controller level because I can't log anything there, so it needs to be done in the middleware or at the server (but I can't find anything for Nginx that lets us deflate). Please assist!
Ok, turns out the iPhone client was sending the wrong headers. So the solution for anyone encountering this is to see the advice here:
Rails: how to unzip a compressed xml request body?
And verify that you are sending Content-Type: gzip/json.

Adobe Flex 3 : Fault Event doesnt return XML Feed sent from Server

I am working on a flex application which communicates with a Rails backened.
When i request for some data, It sends back xml feed.
In some cases, if given parameters are not valid, then rails return an error feed with status code = 422 as following
email is wrong
But I dont get this feed in FaultEvent of Flex, How could i read error feed?
Thanks
Are you getting the result in ResultEvent in such cases? I am not sure for what all HTTP error codes FaultEvent will get invoke(I know only it goes for 404 and 500). May be its still going to ResultEvent as a valid result!
You can use HTTPService instead of URLLoader.
Flex HTTP results will not include the actual underlying HTTP response codes. It just doesn't work. (TM)

Resources