构建 MultipartFormData API 响应

发布于 2025-01-15 14:22:29 字数 685 浏览 1 评论 0原文

我需要构建一个 API,以字节数组形式返回 JSON 对象和附加文件。为此,我想到在 C# 中使用 MultipartFormDataContent 类。我的API是这样写的。

public async Task<IHttpActionResult> MethodName(Params){
    ......statements......
    var responseContent = new MultipartFormDataContent();
    ......statements......
    responseContent.Add(new StringContent(jsonString), 'JSON Object');
    ......statements......
    responseContent.Add(byteArrayContent);
    return responseContent;
}

这会在构建项目时出现错误,无法将responseContent 转换为IHttpActionResult。所以我尝试像这样显式转换。

return (IHttpActionResult)responseContent;

但这会引发无法转换为 IHttpActionResult 的运行时错误。那么我将如何返回responseContent。任何帮助表示赞赏。

I need to build an API that returns a JSON object and attached files in byte array form. So to do this I thought of using MultipartFormDataContent class in C#. I have the API written something like this.

public async Task<IHttpActionResult> MethodName(Params){
    ......statements......
    var responseContent = new MultipartFormDataContent();
    ......statements......
    responseContent.Add(new StringContent(jsonString), 'JSON Object');
    ......statements......
    responseContent.Add(byteArrayContent);
    return responseContent;
}

This is giving an error while building the project about not being able to convert the responseContent to IHttpActionResult. So I tried explicit casting like so.

return (IHttpActionResult)responseContent;

But this throws a runtime error about not being able to convert to IHttpActionResult. So how would I go about returning responseContent. Any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瞳孔里扚悲伤 2025-01-22 14:22:29

返回ResponseMessageResult,支持IHttpActionResult

return new ResponseMessageResult(new HttpResponseMessage() { Content = responseContent })

Return ResponseMessageResult, it supports IHttpActionResult:

return new ResponseMessageResult(new HttpResponseMessage() { Content = responseContent })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文