You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Web API中将字节数组作为类属性传递给OData函数

问题描述

我在ASP.NET Web API中使用OData V4,经过大量调研和实验后,仍然无法将字节数组(byte[])作为类模型属性传递。单独将控制器操作配置为接收byte[]参数时可以正常获取正确数据,仅在byte[]作为类属性传递时会失败,框架报错提示无法将字符串转为字节数组。

相关代码

类模型定义

public class TempFileModel
{
    public string Name { get; set; }
    public byte[] Content { get; set; }
}

OData模型配置

public class TransientFileConfiguration : IModelConfiguration
{
    public void Apply(ODataModelBuilder builder, ApiVersion apiVersion, string routePrefix)
    {
        builder.EntitySet<TransientFileModel>("TransientFiles");
        builder.EntityType<TransientFileModel>().HasKey(e => e.Key);

        builder.Action("UploadFile")
            .Returns<List<string>>()
            .CollectionParameter<TempFileModel>("file");
    }
}

控制器操作代码

[HttpPost]
[ODataRoute("UploadFile")]
public async Task<IHttpActionResult> UploadFile(ODataActionParameters parameters)
{
    var paramValue = parameters["file"];

    return Ok(new List<string>());
}

错误信息

Invalid cast from 'System.String' to 'System.Byte[]'.

错误截图


解决方案

这个错误的根本原因是OData模型构建器没有显式识别TempFileModel的类型结构,其内部的Content属性没有被标记为二进制类型,请求中传输的base64格式字节数组会被默认解析为字符串类型,进而触发类型转换异常。单独传递byte[]参数时OData框架会自动处理类型转换逻辑,但作为自定义类的属性时需要额外配置类型映射规则。

操作步骤

  1. 补充TempFileModel的OData类型配置
    在TransientFileConfiguration类的Apply方法中,新增TempFileModel的复杂类型注册,显式声明Content属性为二进制类型:
public void Apply(ODataModelBuilder builder, ApiVersion apiVersion, string routePrefix)
{
    // 保留原有配置
    builder.EntitySet<TransientFileModel>("TransientFiles");
    builder.EntityType<TransientFileModel>().HasKey(e => e.Key);

    // 新增TempFileModel复杂类型配置
    var tempFileConfig = builder.ComplexType<TempFileModel>();
    tempFileConfig.Property(p => p.Name);
    tempFileConfig.Property(p => p.Content).IsBinary();

    // 原有操作配置保留
    builder.Action("UploadFile")
        .Returns<List<string>>()
        .CollectionParameter<TempFileModel>("file");
}
  1. 可选:简化控制器参数绑定
    无需手动解析ODataActionParameters,可直接声明对应类型的参数,框架会自动完成绑定和类型转换:
[HttpPost]
[ODataRoute("UploadFile")]
public async Task<IHttpActionResult> UploadFile(IEnumerable<TempFileModel> file)
{
    // 直接使用file参数即可,Content属性已自动转换为byte[]
    return Ok(new List<string>());
}

内容的提问来源于stack exchange,提问作者Asad Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 18:24:04