Веб-API c # локально работает, но не работает в Azure после публикации - PullRequest
0 голосов
/ 27 октября 2018

Я получил ошибку ниже. Я пытаюсь реализовать загрузку WEB API в C #, которая загружает большой двоичный объект в файл из хранилища BLOB-объектов Azure.

Я пробовал режим отладки в Visual Studio, но он не работает и выдает ошибки, когда тестируется локально, получая эту ошибку только при развертывании. Я предполагаю, что это может быть путь к файлу, но я не знаю, если честно.

Внутренняя ошибка сервера 500.

[RoutePrefix("api/download")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class DownloadController : ApiController
{
    private ggContext db = new ggContext();
    private const string Container = "ggblobcontainer";
    [HttpGet]
    public HttpResponseMessage GetFile(int audioid)
    {
        //get the object storing the audio 
        Someobject zzz = db.Meetings.Find(audioid);
        //get the filename from the object 
        string fileName = zzz.GetFileName();
        //account information from web.config 
        var accountName = ConfigurationManager.AppSettings["storage:account:name"];
        var accountKey = ConfigurationManager.AppSettings["storage:account:key"];
        var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
        //create blob client from account
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        //get the container with the blobs storing the audio
        CloudBlobContainer audioContainer = blobClient.GetContainerReference(Container);
        //get the specific blob with the filename from object
        CloudBlockBlob blockBlob = audioContainer.GetBlockBlobReference(fileName);
        //if the blob is null error response
        if (blockBlob == null)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "blob with the file name " + fileName + " does not exist in " + Container);
        }
        try
        {
            //cause audio storage name on azure has "" eg. "sick audio file - why is it wrong [LYRICS].mp3" with quotations
            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
            Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
            //replace illegal chars with nothing in case replace the . for .mp3 
            string CleanFileName = r.Replace(fileName, "");
            // download to desktop
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //change it to fileName not dragon little bits 
            string gg = Path.Combine(path, CleanFileName);
            blockBlob.DownloadToFile(gg, FileMode.Create);
        }
        catch (Exception e)
        {
            throw e;
        }
        return Request.CreateResponse(HttpStatusCode.OK, fileName + " was downloaded succesfully");
    }
}

1 Ответ

0 голосов
/ 29 октября 2018

Как упоминалось выше, Environment.GetFolderPath (Environment.SpecialFolder.Desktop) не будет работать в среде сервера.Поэтому вы должны попробовать что-то вроде:

string gg = Path.Combine(Server.MapPath("~\SomeDirectoryName"), CleanFileName)

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...