GetAsync causing timeout issue - c#

I have below code which causing issue while fetching data
var result = client.GetAsync(requestUri).Result;
If I hit requestUri from browser then it works fine. but from above code it gives below error.
Error :
One or more errors occurred.An error occurred while sending the request.The underlying connection was closed: An unexpected error occurred on a send.Authentication failed because the remote party has closed the transport stream.
Stack Trace1 :
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at foo(String resultUrl)
at dooo(String param, String resultUrl)
at foo.<>c__DisplayClass2.<Product>b__0(String x, String y)
at foo[T](Func3 fn) at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
Stack Trace2
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)
at Foo1(String resultUrl)
at Foo2(String param, String resultUrl)
at Foo3.<>c__DisplayClass2.<Product>b__0(String x, String y)
at Foo4(Func3 fn) at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar) at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()
Also i tried awaitable call but no luck. Can we increase request timeout for get request in this scenario.
Awaitable code I tried
var result = await client.GetAsync(requestUri);
if (!result.IsSuccessStatusCode) throw new Exception(string.Format("Unable to receive data from Uri: {0}", uri.ToString()));
// write the results
using (var write = File.Create(filePath))
using (var read = await result.Content.ReadAsStreamAsync())
{
read.Seek(0, SeekOrigin.Begin);
read.CopyTo(write);
}

If the response is talking long time and you want to increase the timeout just set it on the client: https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.timeout(v=vs.118).aspx
Also from looking at the class itself:
TimeSpan defaultTimeout = TimeSpan.FromSeconds(100.0);
TimeSpan maxTimeout = TimeSpan.FromMilliseconds((double) int.MaxValue);
TimeSpan infiniteTimeout = TimeSpan.FromMilliseconds(-1.0);

Related

Forward ASP.Net WebAPI request to another API

I am trying to forward request from one API to another one like this:
protected Task<HttpResponseMessage> ForwardRequestToSomeApi()
{
string forwardUri = "https://some.api" + Request.RequestUri.PathAndQuery;
Request.Headers.Remove("Host");
Request.RequestUri = new Uri(forwardUri);
if (Request.Method == HttpMethod.Get)
{
Request.Content = null;
}
return new HttpClient().SendAsync(Request, HttpCompletionOption.ResponseHeadersRead);
}
but when sending PUT request I get:
Cannot close stream until all bytes are written.
Full exception info:
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred while sending the request.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":"
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"The request was aborted: The request was canceled.","ExceptionType":"System.Net.WebException","StackTrace":"
at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)\r\n
at System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)\r\n
at System.Net.ConnectStream.Dispose(Boolean disposing)\r\n
at System.IO.Stream.Close()\r\n
at System.Net.Http.HttpClientHandler.<>c__DisplayClass109_0.<GetRequestStreamCallback>b__0(Task task)","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Cannot close stream until all bytes are written.","ExceptionType":"System.IO.IOException","StackTrace":"
at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean aborting)"}}}
Inner exception :
IOException Message: "Cannot close stream until all bytes are
written." StackTrace: at
System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean
aborting)
Update:
Provided above code is fully working, the problem was how I attempted to use it. In my main API I had next webapi action:
[HttpPut]
public Task<HttpResponseMessage> Create(string id, Foo model)
{
return ForwardRequestToSomeApi();
}
The problem here is I introduced the model in parameters, thanks to model binding request's content were being read and parsed into model, so when I forward request to another API I send request without content. The fix is to remove all parameters:
[HttpPut]
public Task<HttpResponseMessage> Create()
{
return ForwardRequestToSomeApi();
}

Mongodb C# 'System.TimeoutException

I got strange exception in mongodb.I wrote a simple service into vs and worked well till last night. but now when I am running my service by VS I get this exception:
An exception of type 'System.TimeoutException' occurred in MongoDB.Driver.Core.dll but was not handled in user code
Additional information: A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = ReadPreferenceServerSelector{ ReadPreference = { Mode = Primary, TagSets = [] } }, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "127.0.0.1:27017" }", EndPoint: "127.0.0.1:27017", State: "Disconnected", Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:27017
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.Core.Connections.TcpStreamFactory.<ConnectAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.Core.Connections.TcpStreamFactory.<CreateStreamAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__47.MoveNext()
--- End of inner exception stack trace ---
at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__47.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at MongoDB.Driver.Core.Servers.ClusterableServer.<HeartbeatAsync>d__42.MoveNext()" }] }.
why I got this exception and how could I handle it?
why my service worked well before?
this is where I got this exception:
public static IList<Location> GetFinalLocationsInTopicInLocationTable(string topic)
{
logger.Trace(Constants.LOG_MESSAGE_METHOD_STARTED);
var collection = GetDbMongo().GetCollection<Location>(DB_COLLECTION_LOCATIONS);
var matchFilter = Builders<Location>.Filter.Regex("Topic", topic);
var groupFilter = new BsonDocument { { "_id", "$DeviceId" }, { "max", new BsonDocument("$max", "$CreationDateTime") } };
var location = collection
.Aggregate()
.Match(matchFilter)
.Group(groupFilter)
.ToList(); // -----I got this exception
I resolve that. my problem was:
my mongodb service was stopped. I do not know why it was stopped but when I start it, the problem gone.

Azure Media Services Error 400

I am currently building an app and am trying to write a webjob to
take an mp4file i have uploaded to blob storage and create an asset which i then can encode and prepare to stream using azure media services.
public class Functions
{
// This function will get triggered/executed when a new message is written
// on an Azure Queue called queue.
static string accName = "copied from portal ";
static string accKey = "as above";
static CloudMediaContext context = new CloudMediaContext(accName,accName);
// Use the cached credentials to create CloudMediaContext.
//static CloudMediaContext context = new CloudMediaContext(accName,accKey);
public static void ProcessVideo(
[QueueTrigger("videorequest")] VideoBlobInformation blobInfo,
[Blob("{ProfileId}/{BlobName}", FileAccess.Read)] Stream input,
[Blob("{ProfileId}/{BlobNameWithoutExtension}_stream.mp4")] CloudBlockBlob outputBlob)
{
VideoBlobInformation b = blobInfo;
using (Stream output = outputBlob.OpenWrite())
{
ConvertAndPrepareVideo(b,input, output);
}
// Entity Framework context class is not thread-safe, so it must
// be instantiated and disposed within the function.
using (impulsevidContext db = new impulsevidContext())
{
//var id = blobInfo.ProfileId;
//Video ad = db.Videos.Find(id);
//if (ad == null)
//{
// throw new Exception(String.Format("AdId {0} not found, can't create thumbnail", id.ToString()));
//}
//ad.StreamUrl = outputBlob.Uri.ToString();
//db.SaveChanges();
}
}
public static void ConvertAndPrepareVideo(VideoBlobInformation info,Stream input, Stream output)
{
var storageAccount = new CloudStorageAccount(new StorageCredentials("accnameofstorage", "storage account associated with azure media services"), true);
//output all webjob input blobs into a container -mediacontroller-
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var mediaBlobContainer = cloudBlobClient.GetContainerReference("impfile");
mediaBlobContainer.CreateIfNotExists();
IAsset sourceAsset = context.Assets.Where(a => a.Id == info.VideoId).First();
}
I am using a single storage account that i upload to.
i keep getting this error 400 no matter what i try caused by this line
IAsset sourceAsset = context.Assets.Where(a => a.Id == info.VideoId).First();
which causes this log error
Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.ProcessVideo ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.WebClient.UploadValues(Uri address, String method, NameValueCollection data)
at System.Net.WebClient.UploadValues(String address, String method, NameValueCollection data)
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.<>c__DisplayClass47_2.b__0()
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.<>c__DisplayClass1.b__0()
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction[TResult](Func1 func)
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction(Action action)
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.RefreshToken()
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.GetAccessToken()
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.GetAuthorizationHeader()
at Microsoft.WindowsAzure.MediaServices.Client.OAuth.OAuthDataServiceAdapter.AddAccessTokenToRequest(WebRequest request)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.<>c__DisplayClass21_0.<GetAccountApiEndpoint>b__0()
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.<>c__DisplayClass1.<ExecuteAction>b__0()
at Microsoft.WindowsAzure.MediaServices.Client.TransientFaultHandling.MediaRetryPolicy.ExecuteAction[TResult](Func1 func)
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction(Action action)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.GetAccountApiEndpoint(OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter versionAdapter, Uri apiServer, UserAgentAdapter userAgentAdapter, IWebRequestAdapter clientRequestIdAdapter)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.<>c__DisplayClass24_0.b__0()
at Microsoft.WindowsAzure.MediaServices.Client.Cache1.GetOrAdd(String key, Func1 valueFactory, Func1 expirationFactory)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.CreateAzureMediaServicesEndPoint(Uri azureMediaServicesEndpoint, MediaContextBase mediaContext)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory..ctor(Uri azureMediaServicesEndpoint, CloudMediaContext mediaContext)
at Microsoft.WindowsAzure.MediaServices.Client.CloudMediaContext.get_MediaServicesClassFactory()
at Microsoft.WindowsAzure.MediaServices.Client.AssetCollection.<.ctor>b__2_0()
at System.Lazy1.CreateValue()
at System.Lazy1.LazyInitValue()
at System.Lazy1.get_Value()
at Microsoft.WindowsAzure.MediaServices.Client.AssetCollection.get_Queryable()
at Microsoft.WindowsAzure.MediaServices.Client.BaseCollection1.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable1 source, Expression1 predicate)
at VideoProcess.Functions.ConvertAndPrepareVideo(VideoBlobInformation info, Stream input, Stream output)
at VideoProcess.Functions.ProcessVideo(VideoBlobInformation blobInfo, Stream input, CloudBlockBlob outputBlob)
at lambda_method(Closure , Functions , Object[] )
at Microsoft.Azure.WebJobs.Host.Executors.VoidMethodInvoker1.InvokeAsync(TReflected instance, Object[] arguments)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`1.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__13.MoveNext()
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__10.MoveNext()
context = new CloudMediaContext(new MediaServicesCredentials(
accName,
accKey));
should be set within the ConvertAndPrepareVideo method not outside

How to properly handle Task Exception

I am trying to figure out how to properly handle some exceptions in a Task:
Calling Method:
Task<Branch3GInfo> getActive3GRoutersTask =
Task.Run(
() => CAS.Service.GetBranch3GInformationAsync(3)
);
try
{
Task.WaitAll(discoverRouterExtendedInfoTask, getActive3GRoutersTask);
}
catch(AggregateException aggEx)
{
StringBuilder sb = new StringBuilder();
sb.Append("Some problems occured on GetNodesInCriticalCondition(): \n");
foreach (var ex in aggEx.InnerExceptions)
{
sb.Append(ex.Message);
}
Trace.TraceError(sb.ToString());
}
var branch3gInfo = getActive3GRoutersTask.Result;
var branch3gInfo = getActive3GRoutersTask.Result; throws a System.Aggregate Exception.
Called method:
public async Task<Branch3GInfo> GetBranch3GInformationAsync(int searchDepth)
{
var branch3gInfo = await GetBranch3GInterfacesAsync();
var activeRoutersExtInfos = new List<CasApiRouterModelExtendedInfo>();
foreach (var netInterface in branch3gInfo.Branch3GActiveInterfaces)
{
try
{
var task = GetRouterExtendedInfoFromInterfaceAsync(netInterface, searchDepth);
var result = await task;
if (task.Status == TaskStatus.RanToCompletion && result != null)
{
activeRoutersExtInfos.Add(result);
}
else
{
Trace.TraceError("Error occured trying to get info about Active 3G Router " + netInterface.ModelName + ".");
}
}
catch (Exception ex)
{
Trace.TraceError("Error occured trying to get info about Active 3G Router " + netInterface.ModelName +
": \n" + ex.Message);
}
}
return new Branch3GInfo()
{
Branch3GActiveInterfaces = branch3gInfo.Branch3GActiveInterfaces,
Branch3GCapableInterfaces = branch3gInfo.Branch3GCapableInterfaces,
Branch3GActiveRouters = activeRoutersExtInfos.ToArray()
};
}
From my code, I am making the assumption that GetBranch3GInformationAsync() should be either executing the else clause which doesn't add the result to activeRoutersExtInfos, OR, it should be catching the exception. Why is it that the calling method throws a System.AggregateException if I am handling this in GetBranch3GInformationAsync()?
How do I go about fixing this so that any call to GetRouterExtendedInfoFromInterfaceAsync() that fails due to an exception is ignored, and so that it doesn't break my code?
UPDATE:
Stack trace for the InnerException in System.AggregateException ("The remote server returned an error: (500) Internal Server Error.")
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.CasApiRestCall.<ExecuteAsync>d__38.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Queries\CasApiRestCall.cs:line 294
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<RenderAndExecuteRestCallAsync>d__103.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 2516
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<QueryModelsFilterByAttributeNotDeviceOnlyAsync>d__51.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 1196
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInterfacesAsync>d__34.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 442
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInformationAsync>d__26.MoveNext() in C:\src\CASpectrumApi\src\CASpectrumApi\Managers\CasApiServiceManager.cs:line 246
You can see from your call stack:
at CASpectrumApi.Managers.CasApiServiceManager.<GetBranch3GInterfacesAsync>d__34.MoveNext()
that it is the call to GetBranch3GInterfacesAsync that is failing, not the call to GetRouterExtendedInfoFromInterfaceAsync. GetBranch3GInterfacesAsync is called outside the try block, so naturally the exception will propagate.

Server cannot append header after HTTP headers have been sent uploading files

I get this exception intermittently in my asp.net mvc 5 c# web application:
Server cannot append header after HTTP headers have been sent.
It just happens uploading images to S3 method (Web Api Controller).
The presendrequestheaders in Global.asax
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app != null &&
app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
}
The method that trigger the error:
[HttpPost]
[Route("UploadImageJSON")]
public IHttpActionResult UploadImageJSON(HttpRequestMessage request)
{
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count != 1) return BadRequest();
var postedFile = httpRequest.Files[0];
var contentType = postedFile.ContentType;
if (!contentType.Contains("image"))
{
return StatusCode(HttpStatusCode.NotAcceptable);
}
var keyUploadFiles = Constants.UrlS3Amazon +
S3.UploadToS3WithStream(postedFile.InputStream, contentType);
return Json(JsonConvert.SerializeObject(keyUploadFiles));
}
EDIT: More information... I have my Web App hosted in Elastic BeanStalk with a load balancer, the load balancer has installed a SSL Certificate, and the connection between the load balancer and the EC2 instances are in ports 80. Maybe it could be helpful.
The Elmah log:
System.Web.HttpException (0x80004005): Server cannot append header after HTTP headers have been sent.
at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary2 headers, String key, String[] values)
at Microsoft.Owin.ResponseCookieCollection.Append(String key, String value, CookieOptions options)
at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware1.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Mapping.MapMiddleware.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Thanks!!
have you tried with removing app.Context.Response.Headers.Remove("Server"); i think there is this is the issue?

Categories