Cannot Download File from Api

Hi guys 

im trying to Download uploaded Object From this Url

$"{_mfileUrl}/REST/objects/{FileInfo.ObjVerType}/{FileInfo.ObjVerID}/{FileInfo.ObjVerVersion}/files/{FileInfo.FileID}/content?active-vault={_valut}"

but every time i get following error :

Server cannot set status after HTTP headers have been sent.

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.Web.HttpException: Server cannot set status after HTTP headers have been sent.

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:

[HttpException (0x80004005): Server cannot set status after HTTP headers have been sent.]
   System.Web.HttpResponse.set_StatusCode(Int32 value) +12000000
   MFWS.HttpHandlers.HttpHandler.ProcessRequest(HttpContext context) +1824
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +790
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +88

Note that I get this error when the object is uploaded by api


this is my code for Downloading

public virtual async Task<(byte[] fileBytpe , string filename)> DowanloadObjectAsync(DownloadFileDto FileInfo)
{
try
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
using (HttpClient client = new HttpClient(clientHandler))
{

// Authenticate.
client.DefaultRequestHeaders.Add("X-Authentication", _token);
HttpResponseMessage response = await client.GetAsync($"{_mfileUrl}/REST/objects/{FileInfo.ObjVerType}/{FileInfo.ObjVerID}/{FileInfo.ObjVerVersion}/files/{FileInfo.FileID}/content?active-vault={_valut}");

if (response.IsSuccessStatusCode)
{

byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
string filename = null;
if (response.Content.Headers.ContentDisposition != null)
{
filename = response.Content.Headers.ContentDisposition.FileName.Replace("\"", "");
}
return (fileBytes , filename);
}
else
{
throw new Exception("Failed to download the file. Status code: " + response.StatusCode);
}
}
}
catch (HttpRequestException ex)
{
throw new Exception("An error occurred while downloading the file: " + ex.Message);
}

}



and this is my code for Uploading Objects 

private async Task<ObjectVersion> CreateObject(string FileName, PropertyValue[] propertyValues, Stream file)
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

// Create a HttpClient.
var client = new System.Net.Http.HttpClient(clientHandler);

// Authenticate.
client.DefaultRequestHeaders.Add("X-Authentication", _token);
var VersionByFullName = await GetObjectVersion(propertyValues.FirstOrDefault(x => x.PropertyDef.Equals(0)).TypedValue.Value.ToString());

// Build up information for the new object.
var objectCreationInfo = new ObjectCreationInfo()
{
PropertyValues = propertyValues
};

// Which file do we need to upload?
var localFileToUpload = ConvertStreamToFileInfo(file, FileName);
//https://mfiles.arvandfan.com/REST/objects/0/44/2/files/upload.aspx?_method=POST
// Upload the file and retrieve the upload information.
var uploadFileResponse = await client.PostAsync(new Uri(_mfileUrl + "/REST/files.aspx"),
new System.Net.Http.StreamContent(file));



// Extract the value.
var uploadInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<UploadInfo>(
await uploadFileResponse.Content.ReadAsStringAsync());

// Ensure the extension is set.
// NOTE: This must be without the dot!
uploadInfo.Extension = localFileToUpload.Extension.Substring(1);
uploadInfo.Title = localFileToUpload.Name.Split('.')[0];
uploadInfo.Size = localFileToUpload.Length;

// Add the upload to the objectCreationInfo.
objectCreationInfo.Files = new[] { uploadInfo };

// What type of object are we creating?
const int documentObjectTypeId = 0;

// Execute the post.
// NOTE: http://developer.m-files.com/APIs/REST-API/#iis-compatibility
string url = _mfileUrl + "/REST/objects/" + documentObjectTypeId + ".aspx";
var createObjectResponse = new HttpResponseMessage();
//In this case, there is no need to send the Property Value, that's why we only send the information related to the uploaded file.
if (!VersionByFullName.Length.Equals(0))
{
url = $"{_mfileUrl}/REST/objects/{VersionByFullName.First().ObjVer.Type}/{VersionByFullName.First().ObjVer.ID}/20/files/upload.aspx?_method=POST";
createObjectResponse = await client.PostAsync(new Uri(url),
new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(objectCreationInfo.Files), Encoding.UTF8, "application/json"));

}
//In this case, you need to send Property Value
else
{
createObjectResponse = await client.PostAsync(new Uri(url),
new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(objectCreationInfo), Encoding.UTF8, "application/json"));

}

// Extract the value.
var objectVersion = Newtonsoft.Json.JsonConvert.DeserializeObject<ObjectVersion>(
await createObjectResponse.Content.ReadAsStringAsync());

return objectVersion;
}




Thank you in advance for your reply

Parents Reply Children
No Data