使用低代码平台调用Stable Diffusion生成图像并存储?
解读
国内面试场景下,这道题表面问“低代码”,实则考察候选人能否把C#后端能力嵌入到“全民开发”浪潮中:
- 低代码平台(如钉钉宜搭、腾讯云微搭、简道云、OutSystems中国版)大多支持“自定义API节点”或“C#脚本块”,但运行环境受限(沙箱、内存≤256 MB、超时≤30 s)。
- Stable Diffusion(SD)主流部署在“本地GPU服务器”或“阿里云PAI-EAS/腾讯云TI-ONE”,对外暴露HTTP API,鉴权方式各异(Bearer Token、AK/SK、RTMP签名)。
- 图像存储需符合国内合规:图片先过阿里云内容安全(绿网)或腾讯云天御审核,再落盘到OSS/COS,最后把URL回写到低代码表单子段。
- 面试评分点:
- 能否用最小代码量(低代码思维)完成“调API→审核→落盘→回写”闭环。
- 异常重试、Token刷新、流式下载内存控制。
- 配置与代码分离,方便 citizen-developer 拖拽即用。
知识点
- .NET 6+ HttpClientFactory + Polly:在低代码沙箱里做“熔断+重试”。
- System.Text.Json源生成器:沙箱禁止反射,用JsonSerializerContext降低启动开销。
- 阿里云OSS SDK for .NET:STS临时凭证最小权限上传,避免泄露长期AK。
- 内容安全审核API:同步detect返回label=normal后再上传,否则抛BusinessException。
- 低代码平台约定:返回统一JSON{code,msg,data},data里放OSS URL,前端可直接绑定Image组件。
- 性能陷阱:SD返回PNG约5 MB,沙箱内存小,必须用“流式复制+分片上传”避免一次性load到内存。
答案
以下示例假定低代码平台提供“C#脚本节点”,已注入IConfiguration、ILogger,且平台底层就是.NET 6隔离沙箱。脚本可直接粘贴到节点里, citizen-developer 只需在界面上配4个参数:SD地址、SDToken、OSS STS地址、业务Bucket。
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Polly;
using Polly.Extensions.Http;
public class SdLowCodeService
{
private readonly HttpClient _http;
private readonly IConfiguration _cfg;
private readonly ILogger<SdLowCodeService> _log;
private readonly JsonSerializerContext _jsonCtx;
public SdLowCodeService(HttpClient http, IConfiguration cfg, ILogger<SdLowCodeService> log)
{
_http = http;
_cfg = cfg;
_log = log;
_jsonCtx = SourceGenerationContext.Default;
}
public async Task<string> GenerateAndStoreAsync(string prompt)
{
// 1. 请求Stable Diffusion
var sdRequest = new { prompt, steps = 20, width = 512, height = 512 };
using var req = new StringContent(JsonSerializer.Serialize(sdRequest, _jsonCtx.SdRequest), Encoding.UTF8, "application/json");
var retry = HttpPolicyExtensions.HandleTransientHttpError()
.WaitAndRetryAsync(3, _ => TimeSpan.FromSeconds(2));
using var res = await retry.ExecuteAsync(async () =>
{
var r = new HttpRequestMessage(HttpMethod.Post, _cfg["SdUrl"]) { Content = req };
r.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _cfg["SdToken"]);
return await _http.SendAsync(r, HttpCompletionOption.ResponseHeadersRead);
});
res.EnsureSuccessStatusCode();
// 2. 流式下载图片,内存不超30 MB
var fileName = $"{Guid.NewGuid():N}.png";
await using var imgStream = await res.Content.ReadAsStreamAsync();
// 3. 内容安全审核(同步)
var greenReq = new HttpRequestMessage(HttpMethod.Post, _cfg["GreenUrl"])
{
Content = new StreamContent(imgStream)
};
greenReq.Content.Headers.ContentType = new("image/png");
var greenRes = await _http.SendAsync(greenReq);
greenRes.EnsureSuccessStatusCode();
var green = JsonSerializer.Deserialize<GreenResponse>(await greenRes.Content.ReadAsStreamAsync(), _jsonCtx.GreenResponse);
if (green?.Label != "normal")
throw new InvalidOperationException($"内容审核不通过:{green.Label}");
imgStream.Position = 0;
// 4. STS临时凭证上传OSS
var sts = await GetStsAsync();
var ossClient = new OssClient(sts.Endpoint, sts.AccessKeyId, sts.AccessKeySecret, sts.SecurityToken);
var putReq = new PutObjectRequest(_cfg["BucketName"], fileName, imgStream)
{
Metadata = { ["x-oss-meta-prompt"] = prompt }
};
ossClient.PutObject(putReq);
// 5. 返回HTTPS URL给低代码表单
return $"https://{_cfg["BucketName"]}.{sts.Endpoint}/{fileName}";
}
private async Task<StsToken> GetStsAsync()
{
using var res = await _http.GetAsync(_cfg["StsUrl"]);
res.EnsureSuccessStatusCode();
return JsonSerializer.Deserialize<StsToken>(await res.Content.ReadAsStreamAsync(), _jsonCtx.StsToken);
}
// DTOs
public record SdRequest(string prompt, int steps, int width, int height);
public record GreenResponse(string Label);
public record StsToken(string Endpoint, string AccessKeyId, string AccessKeySecret, string SecurityToken);
}
[JsonSerializable(typeof(SdRequest))]
[JsonSerializable(typeof(GreenResponse))]
[JsonSerializable(typeof(StsToken))]
internal partial class SourceGenerationContext : JsonSerializerContext { }
低代码平台调用方式(伪YAML):
node: CSharpScript
name: 生成商品图
input:
- key: prompt
type: string
required: true
output:
- key: imageUrl
type: url
script: |
var svc = new SdLowCodeService(httpClient, config, logger);
return await svc.GenerateAndStoreAsync(prompt);
至此, citizen-developer 只需在表单里拖一个“文本输入”绑定prompt,再拖一个“图片展示”绑定imageUrl,零编译即可完成“AI生图+合规存储”。
拓展思考
- 高并发场景:把脚本拆成“异步消息+函数计算”,低代码节点只发MQ,C# isolated worker去消费,避免沙箱30 s超时。
- 模型热切换:在OSS放一份“model_config.json”,脚本先拉配置,根据prompt关键词动态路由到不同SD模型(真人/二次元/设计稿)。
- 成本优化:对同一prompt做MD5去重,OSS键名=md5+.png,命中直接返回,减少GPU调用。
- 多租户隔离:STS策略按“bucket+prefix”隔离,prompt中敏感词替换为“*”后再写metadata,防止越权。
- 可观测性:把生成耗时、审核结果、上传字节数写成OpenTelemetry指标,低代码平台自带仪表盘即可查看。
题目导航