c#Web API在本地可用,但发布后在Azure中不起作用

时间:2018-10-27 07:47:02

标签: c# asp.net-web-api download

我遇到了以下错误。我正在尝试在C#中实现下载WEB API,该API将blob从azure blob存储下载到文件中。

我已经在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 :(得分:0)

如上所述,Environment.GetFolderPath(Environment.SpecialFolder.Desktop)无法在服务器环境上工作。因此,您必须尝试以下操作:

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

希望这会有所帮助。