如何在Web API控制器中接收字节数组和json [英] How to receive a byte array and json in a Web API Controller

查看:763
本文介绍了如何在Web API控制器中接收字节数组和json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在c#Web API应用程序中接收一个json对象以及一个字节数组.

I need to receive a json object together with a byte array in a c# Web API application.

这是我发送数据的方式:

This is how I am sending the data:

public bool SendMedia(string method, Media media)
{
    string filePath = Path.GetFullPath(Path.Combine(filesDirectory, media.FileName));
    if (!File.Exists(filePath))
    {
        return false;
    }
    using (var client = new HttpClient())
    using (var content = new MultipartContent() )
    {
        content.Add(new StringContent(JsonConvert.SerializeObject(media), Encoding.UTF8, "application/json"));
        byte[] b = File.ReadAllBytes(filePath);
        content.Add(new ByteArrayContent(b, 0, b.Length));
        var response = client.PostAsync(new Uri(baseUri, method).ToString(), content).Result;
        if (response.IsSuccessStatusCode)
            return true;
        return false;
    }
}

这就是我试图收到的方式:

And this is how I am trying to receive it:

// POST: api/Media
[ResponseType(typeof(Media))]
public HttpResponseMessage PostMedia(Media media, byte[] data)
{
    int i = data.Length;
    HttpResponseMessage response = new HttpResponseMessage();
    if (!ModelState.IsValid)
    {
        response.StatusCode = HttpStatusCode.ExpectationFailed;
        return response;
    }

    if (MediaExists(media.MediaId))
        WebApplication1Context.db.Media.Remove(WebApplication1Context.db.Media.Where(p => p.MediaId == media.MediaId).ToArray()[0]);
    WebApplication1Context.db.Media.Add(media);


    try
    {
        WebApplication1Context.db.SaveChanges();
    }
    catch (DbUpdateException)
    {
        response.StatusCode = HttpStatusCode.InternalServerError;
        return response;
        throw;
    }

    response.StatusCode = HttpStatusCode.OK;
    return response;
}

目前,我对网络开发尚不甚了解.发送MultipartContent是正确的方法吗?

I don't know much about developing for web at the moment. Is sending a MultipartContent the right approach?

推荐答案

框架只能绑定主体中的一项,因此您尝试执行的操作将不起作用.

The framework can only bind one item from the body so what you are trying to attempt would not work.

相反,请像发送请求一样阅读请求内容并提取部分.

Instead, read the request content just as you sent it and extract the parts.

[ResponseType(typeof(Media))]
public async Task<IHttpActionResult> PostMedia() {

    if (!Request.Content.IsMimeMultipartContent()) { 
        return StatusCode(HttpStatusCode.UnsupportedMediaType); } 

    var filesReadToProvider = await Request.Content.ReadAsMultipartAsync(); 

    var media = await filesReadToProvider.Contents[0].ReadAsAsync<Media>(); 
    var data = await filesReadToProvider.Contents[1].ReadAsByteArrayAsync();

    int i = data.Length;

    if (!ModelState.IsValid) {
        return StatusCode(HttpStatusCode.ExpectationFailed);
    }

    if (MediaExists(media.MediaId))
        WebApplication1Context.db.Media.Remove(WebApplication1Context.db.Media.Where(p => p.MediaId == media.MediaId).ToArray()[0]);
    WebApplication1Context.db.Media.Add(media);


    try {
        WebApplication1Context.db.SaveChanges();
    } catch (DbUpdateException) {
        return StatusCode(HttpStatusCode.InternalServerError);
    }

    return Ok(media);
}

还请注意,在您的原始代码中,您声明该操作具有[ResponseType(typeof(Media))],但从未返回该类型的对象.上面的答案包括Ok(media)响应中的模型.

Note also that in your original code you state the the action has a [ResponseType(typeof(Media))] but an object of that type was never returned. The above answer includes the model in the Ok(media) response.

这是一个非常简化的示例.添加任何必要的验证.

The is a very simplified example. add any validation as necessary.

这篇关于如何在Web API控制器中接收字节数组和json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆