DotNetCore error Reading the request body timed out - asp.net-core-3.1

We have deployed our DotNetCore Api to OpenShift after containerizing it.
Recently we observed that few POST requests are throwing 500 error. Below is the stack trace
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Reading the request body timed out due to data arriving too slowly. See MinRequestBodyDataRate.
at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.ReadAsyncInternal(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory`1 buffer, CancellationToken cancellationToken)
at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext
Few solutions from StackOverflow show to update Program.cs with UseKestral with setting MinRequestBodyDataRate.
we are unable to reproduce this error when we run the Docekr Image in our local, is there a hack to reproduce this error.
The other way I tried it from Postman I have the content-length as some value 1000 and gave the post request body less than 1000, rather than calculating at when the request is sent. In that case Iam able to see the error "Reading the request body timed out".
How can I determine if this issue is because of Content-Length Header. I tried to see the request headers using Serilog, but not able to see them. Below is my SeriLog Configuration
options.EnrichDiagnosticContext = (diagnoticsContext, httpContext) =>
{
var request = httpContext.Request;
diagnoticsContext.Set("Custom Header Value", request.Headers["Content-Length"].ToString());
};
Other thing I found was for the POST Request that are showing the timed our errors have logged the time greater than 5 seconds
Did anyone face this error, any ideas on how to fix this ?

Related

Download offline version of images and display in xamarin forms

in my app I would like to program an "offline version" of an display. That is, you can decide in advance to download the images and later videos and then view them without mobile data (due to network coverage), for example.
I use step 1 (Xamarin.Forms: How to download an Image, save it locally and display it on screen?) to download the file.
Step 2 I can not use because the maximum data size is exceeded for larger files. So I use PCLStorage and save the file locally.
IFolder folder = FileSystem.Current.LocalStorage;
IFile file = await folder.CreateFileAsync(imageFileName, CreationCollisionOption.ReplaceExisting);
await file.WriteAllTextAsync(Convert.ToBase64String(imageAsBase64String));
Now I want to display the images again, but no matter what I do, the image is not shown.
I rewrite the imagesource URL to the local file. No matter if only with "filename.jpg" or "file:///data/user/0/com.xxx.yyy_app/files/filename.jpg" no image is shown.
But I can't even check if the image was downloaded correctly as such, because the files in localstorage are not shown in a filemanager. folder.CheckExistsAsync says that the file exists.
Partly I get this error:
[0:] Image Loading: Error getting stream for file:///data/user/0/com.xxx.yyy_app/files/2_76_1.jpg: System.InvalidOperationException:
An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.
at System.Net.Http.HttpClient.PrepareRequestMessage (System.Net.Http.HttpRequestMessage request) [0x0008a] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:678
at System.Net.Http.HttpClient.SendAsync (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) [0x00020] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:437
at System.Net.Http.HttpClient.GetAsync (System.Uri requestUri, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:311
at System.Net.Http.HttpClient.GetAsync (System.Uri requestUri, System.Threading.CancellationToken cancellationToken) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:299
at Xamarin.Forms.StreamWrapper.GetStreamAsync (System.Uri uri, System.Threading.CancellationToken cancellationToken, System.Net.Http.HttpClient client) [0x00011] in D:\a\1\s\Xamarin.Forms.Core\StreamWrapper.cs:99
at Xamarin.Forms.Forms+AndroidPlatformServices.GetStreamAsync (System.Uri uri, System.Threading.CancellationToken cancellationToken) [0x0003f] in D:\a\1\s\Xamarin.Forms.Platform.Android\Forms.cs:854
at Xamarin.Forms.UriImageSource.GetStreamAsync (System.Uri uri, System.Threading.CancellationToken cancellationToken) [0x000cf] in D:\a\1\s\Xamarin.Forms.Core\UriImageSource.cs:136
Long story short: I want to download an image and display it from the local file system. How do I do that?
Thanks a lot for the help.
Translated with www.DeepL.com/Translator (free version)
I want to download an image and display it from the local file system. How do I do that?
The correct steps
Download Image from remote url .
Save it into disk locally .
Get the steam data via the path(folder+fileName).
Display it on Image .
This solution works well but in your scenario the difference that the image size is too big , so we just need to replace Xamarin.Essentials.Preferences with built-in File Handling, cause the later one can handle large file storage .
Modify the method SaveToDisk and GetFromDisk .
string folder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
public static void SaveToDisk(string imageFileName, byte[] imageAsBase64String)
{
var fileName = Path.Combine(folder ,imageFileName);
File.WriteAllText(fileName , Convert.ToBase64String(imageAsBase64String));
}
public static Xamarin.Forms.ImageSource GetFromDisk(string imageFileName)
{
var fileName = Path.Combine(folder ,imageFileName);
var imageAsBase64String = File.ReadAllText(fileName)
return ImageSource.FromStream(() => new MemoryStream(Convert.FromBase64String(imageAsBase64String)));
}

Big Delay in ImapClient, SmtpClient and Pop3Client Connect method when using secure connection

I notice up to 13 sec delay when trying to connect SMTP or IMAP client from MailKit. It seems the delay happens on the call to AuthenticateAsClient method inside MailKit library. I found explanation for the problem here https://blogs.msdn.microsoft.com/alejacma/2011/09/27/big-delay-when-calling-sslstream-authenticateasclient/
This is not an issue in MailKit but I want to know the best workaround for this problem using MailKit. It seems cancellationToken passed to MailKit Connect method is not cancelling this method call. This is a problem when you want to shutdown your process while SmtpClient is connecting, because you want to wait the dedicated thread that runs this code to complete.
This is the workaround I have but it is not very elegant
public override void Connect(string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default(CancellationToken))
{
var connectionTask = smtpClient.ConnectAsync(host, port, options, cancellationToken);
Task.WhenAny(connectionTask, cancellationToken.WhenCanceled()).GetAwaiter().GetResult();
cancellationToken.ThrowIfCancellationRequested();
}
public static class Extensions
{
public static Task WhenCanceled(this CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
}
This above will work most of the time but if cancel the token the connection will stay in connecting state (because AuthenticateAsClient is not cancellable) and the user might attempt to execute another command while the smtpClient is still trying to connect.
I am looking for better approach for cancelling the Connect method in the context of MailKit.

Umbraco Forms An item with the same key has already been added

I are running Umbraco 7.4.5 with Dialogue 1.1 fanoe starter kit and Forms 4.3.3.
I have created a contact form and tested. all works great.
Now created and entire new form gathering entirely different information and put it on its own page. Are calling this for Dialogues when a user is not permitted to access to a topic.
Now I get this error when ever I try to submit either form.
An item with the same key has already been added.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: An item with the same key has already been added.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: An item with the same key has already been added.]
Umbraco.Core.Cache.HttpRuntimeCacheProvider.GetCacheItem(String cacheKey, Func1 getCacheItem, Nullable1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, CacheDependency dependency) +963
Umbraco.Core.Cache.HttpRuntimeCacheProvider.GetCacheItem(String cacheKey, Func1 getCacheItem, Nullable1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, String[] dependentFiles) +107
Umbraco.Core.Cache.DeepCloneRuntimeCacheProvider.GetCacheItem(String cacheKey, Func1 getCacheItem, Nullable1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, String[] dependentFiles) +114
Umbraco.Forms.Core.Cache.CacheProviderExtensions.GetCacheItem(IRuntimeCacheProvider provider, String cacheKey, Func1 getCacheItem, Nullable1 timeout, Boolean isSliding, CacheItemPriority priority, CacheItemRemovedCallback removedCallback, String[] dependentFiles) +225
Umbraco.Forms.Data.StringHelper.ParseMemberPlaceholders(String value, Object memberKey) +1600
Umbraco.Forms.Data.StringHelper.ParsePlaceHolders(HttpContext context, Record record, String value) +390
Umbraco.Forms.Data.StringHelper.ParsePlaceHolders(Record record, String value) +61
........
If I delete the secound form in the backoffice (under Forms) the contact form works.
Has anyone got any surgestions where I start.

Expiring Authentication Redirect Causes GET instead of POST

I have a page where users are editing some content. If the authentication on that page expires, and they press the "Save" button, since their session is timed out, they are redirected to the login page. However, when they re-authenticate, the redirect does a GET on the page when I'm expecting a POST, so it generates a HttException "A public action method 'Close' was not found on controller 'HLPUSD.HEAT.Web.Controllers.TicketController."
What do I need to do to resolve this?
EDIT
Exception:
System.Web.HttpException (0x80004005): A public action method 'SavePrecedence' was not found on controller 'HLPUSD.HEAT.Web.Controllers.QueueController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
If you respect the following conventions:
public ActionResult Foo()
{
...
}
[HttpPost]
public ActionResult Foo(SomeViewModel model)
{
...
}
where the first action renders a form and the second action is used to handle the submission of this form it will work as you have both GET and POST actions for this resource and in the described scenario the users will simply be redirected to GET /SomeController/Foo which will simply render the form once again.

Workflow persistence - WebServiceInputActivity

alt text http://home.elka.pw.edu.pl/~pkolodzi/Capture.PNG
I have created the IAdder interface with two methods: PassA and PassB. My workflow starts with webServiceInputActivity1 which is activated by PassA remote call. Another element in my workflow is another webServiceInputActivity2 element. This time the "IsActivating" property is set to false. I expect my workflow to be persisted after first activity finishes (which does return void). The workflow should be reactivated by calling PassB web method.
After publishing workflow as web service and invoking PassA here is what I get:
System.InvalidOperationException: Workflow with id "b0c5f9dd-57f3-427f-b172-17d4663f7eaf" not found in state persistence store.
at System.Workflow.Runtime.Hosting.PersistenceDBAccessor.RetrieveInstanceState(Guid instanceStateId, Guid ownerId, DateTime timeout)
at System.Workflow.Runtime.Hosting.SqlWorkflowPersistenceService.LoadWorkflowInstanceState(Guid id)
at System.Workflow.Runtime.WorkflowRuntime.InitializeExecutor(Guid instanceId, CreationContext context, WorkflowExecutor executor, WorkflowInstance workflowInstance)
at System.Workflow.Runtime.WorkflowRuntime.Load(Guid key, CreationContext context, WorkflowInstance workflowInstance)
at System.Workflow.Runtime.WorkflowRuntime.GetWorkflow(Guid instanceId)
at System.Workflow.Activities.WorkflowWebService.Invoke(Type interfaceType, String methodName, Boolean isActivation, Object[] parameters)
at PersistanceWebServiceWorkflow.Workflow1_WebService.PassA(Int32 a) in C:\Users\djpiter\AppData\Local\Temp\2dnwfnsn.cs:line 39
Do you have any ideas what I do wrong?
ps:( The database is properly set. I tested it on workflow hosted in console app and delay activity .I also added necessary line to web.config file. )
Kind Regards
PK
If one of your activities would throw an exception, the workflow state information would be deleted from the database. Run your workflow debugger with "break when exception is throw" configured in Debug - Exceptions - Common Language Runtime Exceptions