【发布时间】:2020-05-24 08:37:10
【问题描述】:
我正在尝试将带有一些参数(文件名、相关 ID 等)的二进制文件发送到我的 .Net Core 3 WebAPI 端点。
我的端点如下所示:
[HttpPost, Route("/api/attachment")]
[RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)]
public async Task<IActionResult> Create([FromForm] AttachmentCreateRequest request)
{
我试图返回并转换为我的 POCO 的模型是:
public class AttachmentCreateRequest
{
public string Description { get; set; }
public Guid TransactionId { get; set; }
public IFormFile File { get; set; }
}
当我发送请求时,Chrome 工具会指示正在发送:
------WebKitFormBoundaryXrahZqoiAk4lYBgv Content-Disposition: form-data;名称=“文件”; filename="eBay_订单详情.pdf" 内容类型:application/pdf
------WebKitFormBoundaryXrahZqoiAk4lYBgv Content-Disposition: form-data; name="transactionId"
762505fe-81bd-4b07-9456-cf7f0bb70efb ------WebKitFormBoundaryXrahZqoiAk4lYBgv Content-Disposition: form-data;名称="描述"
测试 ------WebKitFormBoundaryXrahZqoiAk4lYBgv--
我尝试发送的字段是名为“file”的文件、在上面的数据中似乎可见的 transactionId,以及我将其设置为“test”的名为“description”的字段。
但是方法上的断点,显示为null:
为什么我的文件参数会为空?
关于我的应用程序的详细信息: 我使用通用的 Fetch 方法进行所有调用。在我打的电话中,'isBinary' 是真的。
const fetchData = ({ method = 'GET', URL, data = {}, isBinary = false}) => {
// Force the content type.
console.log("FetchData got request:", data)
const contentType = isBinary ? undefined : 'application/json'
const header = {
'Content-Type': contentType,
Accept: contentType,
};
console.log("content type will be", contentType)
// If we have a bearer token (User seems to be signed in), add it to the header.
const userIsAuthenticated = Auth.isAuthenticated();
if (userIsAuthenticated) {
header.Authorization = `Bearer ${Auth.token()}`;
}
// Create the config that will be used for the fetch.
let config = {
method,
headers: header,
};
// If this is anything but a GET, set the body to hold the data we're posting.
if (method !== 'GET' && method !== 'DELETE') {
if(isBinary)
{
console.log("IsBinary.. on't stringify")
config = Object.assign({}, config, { body: data });
}
else
{
const stringified = JSON.stringify(data);
console.log("Body is: ", stringified)
config = Object.assign({}, config, { body: stringified });
}
}
console.log("Fetch: ", config)
// Use the browser api, fetch, to make the call.
return fetch(URL, config)
.then((raw) => {
return raw;
})
.then((response) => {
return response;
})
.catch((e) => {
console.timeEnd(`fetchExecutionTime ${URL}`)
console.log(`An error has occured while calling the API. ${e}`);
});
};
“数据”字段已定义:
let data = new FormData()
data.append('file', this.state.selectedFile)
data.append('transactionId', this.state.transaction.id)
data.append('description', 'test')
console.log("Data now", data)
.. 其中 'selectedFile' 来自选择文件的表单控件。我“附加”了我的 POCO 对象所期望的三个属性。
【问题讨论】:
标签: c# asp.net-web-api