c# - 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");
}
}
解决方案
如上所述,Environment.GetFolderPath(Environment.SpecialFolder.Desktop) 不会在服务器环境中工作。所以你必须尝试类似的东西:
string gg = Path.Combine(Server.MapPath("~\SomeDirectoryName"), CleanFileName)
希望这会有所帮助。
推荐阅读
- python - 由于 EnvironmentError 无法安装软件包:[Errno 2] 没有这样的文件或目录 \\METADATA
- wordpress - 如何在 WordPress 中更改博客终端的字体和背景颜色?
- r - 如何强制列表对象键入“整数”,R中的错误
- java - 带有文件的 AmazonS3Client.putObject 保持对文件的开放引用
- c - 如何在c中使用exec多次运行ping
- c - 字符串文字可以与 char* 连接吗?
- java - 以下类的超类型无法解析。请确保您在类路径中具有所需的依赖项:
- mongodb - 在创建期间强制 MongoDB 副本集使用 IP 而不是主机名
- javascript - 在对象数组中出现空错误
- python - 创建空数据框并向其中添加行