首页 > 解决方案 > c# web API 在本地工作,但在发布后在 Azure 中不起作用

问题描述

我得到了以下错误。我正在尝试在 C# 中实现下载 WEB 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");
    }
}

标签: c#asp.net-web-apidownload

解决方案


如上所述,Environment.GetFolderPath(Environment.SpecialFolder.Desktop) 不会在服务器环境中工作。所以你必须尝试类似的东西:

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

希望这会有所帮助。


推荐阅读