如何通过命令式绑定设置Azure Blob的Content Type为text/json
问题:Azure Functions命令式Blob绑定如何设置内容类型为text/json?
我正在编写Azure Functions,通过Service Bus触发器将数据写入Blob,因需手动指定Blob输出文件名,使用了如下命令式绑定代码,当前代码可正常运行,但Blob默认内容类型为application/octet-stream,请问如何通过命令式绑定将其修改为text/json?
[FunctionName("Usage")] public async Task Run([ServiceBusTrigger("Usage", "UsageFuncProc", Connection = "UsageFunctionsServiceBus")]ServiceBusReceivedMessage sbusMessage, Binder binder) { // ... 其他逻辑 var attributes = new Attribute[]{ new BlobAttribute($"{Utilities.GetContainerName("BlobContainerName")}/{distFormatted}{timestamp}_{entity.ClientId}_{entity.MessageType}.json", FileAccess.Write), new StorageAccountAttribute("AzureWebJobsStorage") }; using (var writer = await binder.BindAsync<TextWriter>(attributes)){ await writer.WriteAsync(jsonEntity); } }
解决方案
直接绑定TextWriter无法设置Blob的元数据(包括内容类型),需要改为绑定到CloudBlockBlob类型,手动配置属性后再写入内容:
[FunctionName("Usage")] public async Task Run([ServiceBusTrigger("Usage", "UsageFuncProc", Connection = "UsageFunctionsServiceBus")]ServiceBusReceivedMessage sbusMessage, Binder binder) { // ... 其他逻辑 var attributes = new Attribute[]{ new BlobAttribute($"{Utilities.GetContainerName("BlobContainerName")}/{distFormatted}{timestamp}_{entity.ClientId}_{entity.MessageType}.json", FileAccess.Write), new StorageAccountAttribute("AzureWebJobsStorage") }; // 绑定到CloudBlockBlob而非TextWriter var blob = await binder.BindAsync<CloudBlockBlob>(attributes); // 设置内容类型为text/json blob.Properties.ContentType = "text/json"; // 写入JSON内容 await blob.UploadTextAsync(jsonEntity); // 提交属性修改 await blob.SetPropertiesAsync(); }
关键说明
- 替换
TextWriter绑定为CloudBlockBlob,这样可以直接操作Blob的属性 - 设置
ContentType后,必须调用SetPropertiesAsync才能将属性变更同步到存储服务 - 如果需要设置其他元数据(如缓存策略、自定义标签),也可以通过
blob.Properties或blob.Metadata进行配置
内容的提问来源于stack exchange,提问作者Kenbo
相关产品推荐
相关产品推荐

