Webap, Unable to read the entity body in Bufferless mode. The request stream has already been buffered - asp.net-web-api2

I am trying to do a fileupload in the webapi and having issues.
The execution is getting failed at this line:
var result = await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<HttpResponseMessage>(t => {..})
Hence I kept a code to see even if the content is rendered at the top of the above code as:
Request.Content.ReadAsStringAsync().Result
Now the error says.
"Unable to read the entity body in Bufferless mode. The request stream
has already been buffered."

Finally I have resolved this issue.
For some reason the framework wasn't liking the below code in WebAPIConfig.cs
config.Services.Replace(typeof(IHostBufferPolicySelector), new WebHostBufferPolicySelector());
I have commented this line and my code started working.
The only change I have seen is I have upgraded my .net framework to 4.6.1 and I think we no longer need this configuration for the newer frameworks.

Related

CefSharp.BrowserSubProcess.Core WCF pipe failure

Our application is using CefSharp version 73.1.130. The issue only occurs on a small number of internal workstations within our organization. Worth noting, we are also seeing the same error with CefSharp version 92. Another strange thing is that it the issue is consistent, but only when the web apps are launched through certain navigations. Other navigations work consistently for these users.
We use RegisterJsObject to register a javascript object with browser. If I understand correctly, asynchronous binding is preferred moving forward.
The issue presents as strange/unexpected behavior in the hosted web application due to failure to retrieve context from the host WinForms application. The behavior would suggest a failure to register/bind the js object with the RegisterJsObject method. However, that method is not throwing an exception.
Enabled Cef logging showed the following error:
ERROR:JavascriptRootObjectWrapper.cpp(34)] IBrowserProcess is null, unable to bind object
After looking into the code, it appears the location that the value pointed to by "IBrowserProcess" is set is in WcfEnabledSubProcess::OnBrowserCreated (https://github.com/cefsharp/CefSharp/blob/cefsharp/73/CefSharp.BrowserSubprocess.Core/WcfEnabledSubProcess.cpp). I was able to build CefSharp and add additional logging to that method.
On my workstation (I'm not affected by the issue), I get through OnBrowserCreated with no exceptions. However, on my coworkers workstation I see the following line is failing:
...
channelFactory->Open();
auto browserProcess = channelFactory->CreateChannel();
auto clientChannel = ((IClientChannel^)browserProcess);
try
{
clientChannel->Open(); <-- FAILS
browser->ChannelFactory = channelFactory;
browser->BrowserProcess = browserProcess;
}
catch (Exception^)
{
}
}
With the error:
There was an error reading from the pipe: The pipe has been ended. (109, 0x6d)
Has anyone seen this issue before? I'm not sure how much this will help, but does anyone know if it's possible to enable WCF tracing with the CefSharp.BrowserSubProcess.exe. I have been trying this, but no luck so far.

Deserializing Media field fails in Piranha CMS

Modifying Piranha for 'headless' scenario: I separated the api into its own REST API, and the MVC into its own UI that calls the REST API. Mostly it works well, but now an obstacle. My REST API serializes the result from the Piranha api, and my MVC web deserializes it into a Piranha StandardPage type. This works for all fields except Media, which is always null. Using newtonsoft.Json.
The Media property is defined in Piranha.Extend.Fields.MediaFieldBase with internal set, which explains why I can't deserialize into it. So I added a [JsonProperty] attribute to the Media property. Once I did this, then the Media field was correctly deserialized by the MVC, and images appeared.
But then I found this broke something else: in the manager, when I try to save a page with a Hero image, the Save buttons spins, stops as though it succeeded, but the toast never appears saying success. I set Debug logging for Microsoft.AspNetCore.Mvc.Infrastructure, and see there's a model state error when this happens:
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed controller factory for controller Piranha.JA.Manager.Controllers.PageApiController (Piranha.JA.Manager)
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter[1]
The request has model state errors, returning an error response.
dbug: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Request was short circuited at action filter 'Microsoft.AspNetCore.Mvc.Infrastructure.ModelStateInvalidFilter'.
I can debug into the PageApiController for most operations, but when Save executes none of the breakpoints are hit.
I also tried just removing the internal accessor from set (and removing [JsonProperty]) and got the same behavior: can deserialize Media ok but trying to save page with a Hero from manager gives model state error.
Would love to write up some documentation on how to go headless if we can solve this.
We've been debugging this one for a few days, can anyone help?
In the branch I pushed I actually changed the accessor to public, so you shouldn’t need the additional attribute. This is also merged to master and will be released in 8.3.
Regards
I posted this on the Piranha CMS github and one of its authors, Hakan Edling, answered in just a few hours:
"The root issue is that when a new item is selected in the manager in the media picker, the media model that is assigned contains a formatted string size "xxx kb". When ASP.NET tries to deserialize this into a long it fails.
So changing the following line in the .vue components for the media-based fields:
this.model.media = media;
to
this.model.media = {
id: media.id,
folderId: media.folderId,
type: media.type,
filename: media.filename,
contentType: media.contentType,
publicUrl: media.publicUrl,
};
Resolves the serialization error in the manager when the Media property is public.. I'll push this fix to a new branch so you can test it."
And soon after,
"Please test with the branch https://github.com/PiranhaCMS/piranha.core/tree/features/make-mediafield-media-public"
I still must add the [JsonProperty] attribute to the Media field in MediaFieldBase class, so my deserializer can access the internal set method. Hakan's fix makes it so this attribute doesn't break the manager.
Thank you for your quick response Hakan, you rock!

MVC4- An asynchronous operation cannot be started at this time --- code works fine on MVC3

I converted a project from MVC3 to MVC4 and also from Entity Framework 5 to EF 6.1. In the code there is a VBHTML page that has a code section "Using Html.BeginForm.... end using". in this page, a user can select a file and click submit. That calls a POST method in a controller. The method in the controller uploads the selected file to Google drive using resumable uploader (aynchronous) of GData API. ResumableUploader has to be used (GData API restrictions for uploading PDF and big files). Now, this code has always worked in the past in MVC3. As soon as the platform was changed to MVC4, started getting this exception:
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%# Page Async="true" %>
at System.Web.AspNetSynchronizationContext.OperationStarted() at Google.GData.Client.ResumableUpload.ResumableUploader.AsyncStarter
(AsyncResumableUploadData data, WorkerResumableUploadHandler workerDelegate,
Object userData)
I did put #Page Async="true" in the VBHTML page, but that did not help. I am 100% sure this is related to MVC4 and/or .Net 4.5 because no other change has been done in the code (other than moving to MVC4 and moving to .Net4.5). I have two code branches now, one on MVC3 and one on MVC4. When I compile MVC3 and copy the output DLL in the app, the above issue does not surface. When I replace that DLL by MVC4 version, the above issue comes up. How to handle this?
This is the code that causes this issue:
Dim auth As Authenticator = New AuthSubAuthenticator("MyToken", authFactory.Token)
Dim uploader As New ResumableUploader(10485760)
AddHandler uploader.AsyncOperationCompleted, AddressOf UploaderCompleted
uploader.InsertAsync(auth, file, New Object())
The trace shows that the exception was thrown from the last line (uploader.InsertAsync)
I understand there is a await method that I could use. Did not try, instead, changed uploader.InsertAsync to uploader.Insert and the code works ok. But but the user has to wait until the upload is complete (for bigger files, for quite a while).
I am 100% sure this is related to MVC4 and/or .Net 4.5
Yes, this is a change in ASP.NET 4.5. However, it's important to note that the code was technically wrong before. ASP.NET 4.5 adds several safeguards to catch improper asynchronous usage. So, the MVC3 code was actually improper; it just wasn't getting caught and reported as such.
changed uploader.InsertAsync to uploader.Insert and the code works ok. But but the user has to wait until the upload is complete (for bigger files, for quite a while).
This is the "proper" way to do it on ASP.NET (on a side note, using await would be more efficient than Insert). ASP.NET is not designed to do work without a user connection.
Consider, for example, what would happen if the upload errors out; there's no way to notify the user that the upload in fact did not complete. For that matter, there's no way to notify the user that the upload did complete. Also, ASP.NET may recycle your application, which can kill an in-progress upload. For these reasons, doing "fire and forget" work is not recommended on ASP.NET.
However, if you're willing to live with those limitations, I describe on my blog a variety of ways to do fire and forget on ASP.NET. Note that ASP.NET 4.5.2 added a built-in way to do this: HostingEnvironment.QueueBackgroundWorkItem.

kSoap-2 android nullpointer exception

I am working with ksoap2 for android and I am sending SOAP requests. I was googling for a whole day and couldn't find solution for my problem. The first problem was with i:type, my service was returning fault for requests with i:type, so I found that this can be fixed using
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
instead of
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
and that fixed the i:type problem. Now the generated request doesn't contain i:type and if I send it using SOAP UI it works fine, but now I get NullPointerException
in this line
httpTransport.call(DEFAULT_SOAP_ACTION, envelope);
Can anyone help me out with this? If u need my code I can post it. I also tried using different versions of ksoap .jar file and it didn't help.
Maybe someone will need this.
I solved this by setting types explicitly (for each PropertyInfo there is .setType function which receives type class String.class etc.) and use
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
and using that removes i:type from the soap request. Hope it will help someone.

WebAPI hangs indefinitely when receiving a POST with incorrect Content-Length in header

I have a project set up using ASP.NET WebAPI on top of Azure, and am having a problem whenever I try to make an HTTP Post where the content-length is too long in the header.
Normally I would've just ignored this problem, because you should be correctly setting the content-length on POST, but it turns out that when this happens, it causes the session to hang indefinitely, and then the Azure emulator crashes.
I have a custom JSON Formatter which extends MediaTypeFormatter, and I set a breakpoint on the first line of my implementation of OnReadFromStreamAsync(). However, the breakpoint is never hit because the hangup happens before ever hitting the JSON Deserializer.
I really have no idea where this hanging is occurring from because I receive no exception, just an indefinite hang and occasional Azure emulator crash.
Thank you in advance for any help or insight you might provide!
This sounds like a bug. The good thing is that you can get updated developer bits form codeplex.
There is a chance what your experiencing is related to one of these:
WebAPI: Stream uploading under webhost is not working
DevDiv 388456 -- WebHost should not use Transfer-Encoding chunked when
content length is known.
Zero ContentLength without content type header in body is throwing
If the updated bits don't fix your problem I suggest you try the standard media formatters to rule in/out your formatter. Failing that, then submit an issue.