使用RestSharp发送HTTP POST Multipart / form-data字段

时间:2022-08-22 19:29:55

I'm having issues using RestSharp for a REST API I need to use for a project I'm working on. The request I need to issue is in three parts: A header API key, a file to upload, and a bunch of data in JSON format. The API requires that the data part be sent using a form field name of "data". For some reason this is causing issues since it's naming the field "data" within the body of the request.

我在使用RestSharp进行REST API时遇到问题,我需要将其用于我正在进行的项目。我需要发出的请求分为三部分:头API密钥,要上传的文件和一堆JSON格式的数据。 API要求使用表单字段名称“data”发送数据部分。出于某种原因,这会导致问题,因为它在请求正文中命名字段“data”。

The code I have as is as follows:

我的代码如下:

var request = new RestRequest(UPLOAD_DOC_URLSEGMENT, Method.POST)
{
    RequestFormat = DataFormat.Json,
    AlwaysMultipartFormData = true,
    JsonSerializer = new RestSharpJsonDotNetSerializer(customSerializer)
};

if (doc is DocA)
    request.AddParameter("data",doc as DocA,ParameterType.RequestBody);
    //request.AddBody(doc as DocA);
else
    request.AddParameter("data", doc as DocB,ParameterType.RequestBody);
    //request.AddBody(doc as DocB);

request.AddFile("file", doc.File.FullName);

As you can see I've attempted to use both the request.AddBody(doc) method and the request.AddParameter(name, object, type) method. Neither of them appear to be sending the data properly because I receive a response from the server saying required parameters are missing. Using fiddler I can see the binary data, but never the JSON data with both of these methods. I've gone through the RestSharp documentation, but I can't find anything that allows me to specify a particular "field" name as "data" for the form data body, which is what I believe is causing the issue I'm having. What am I doing wrong here?

如您所见,我试图同时使用request.AddBody(doc)方法和request.AddParameter(name,object,type)方法。它们似乎都没有正确发送数据,因为我收到服务器的响应,说明缺少必需的参数。使用fiddler我可以看到二进制数据,但从来没有使用这两种方法的JSON数据。我已经浏览了RestSharp文档,但我找不到任何允许我为表单数据体指定特定“字段”名称作为“数据”的内容,这是我认为导致我遇到的问题。我在这做错了什么?

EDIT: Upon further inspection with fiddler it appears that it's not adding my JSON data at all to the body of the HTTP request. However, with a break point right before the upload (execute command) I can see everything serialized properly within the parameter list (and file list). When inspecting the with Fiddler I see the file binary data, and then a multipart/form-data boundary, and then nothing. I would assume this is where my data is supposed to be...

编辑:进一步检查fiddler后,它似乎没有将我的JSON数据添加到HTTP请求的主体。但是,在上传(执行命令)之前有一个断点,我可以在参数列表(和文件列表)中看到所有序列化的内容。当用Fiddler检查时,我看到文件二进制数据,然后是多部分/表格数据边界,然后什么都没有。我认为这是我的数据应该是...

2 个解决方案

#1


7  

So I am doing this by working around a problem with using the AddBody method which automatically kills the multi part form images and will not send them. You must use add parameter instead.

所以我通过解决使用AddBody方法的问题来做到这一点,该方法自动杀死多部分表单图像并且不会发送它们。您必须使用add参数。

To solve this problem you may have to do a little work on both sides of the communication.

要解决这个问题,您可能需要在通信的两个方面做一些工作。

To send the message from the client you do the following:

要从客户端发送消息,请执行以下操作:

new RestRequest("<Your URI>");
request.AddParameter("request", tokenRequest.ToJson());
request.AddFile("front", frontImage.CopyTo, "front");
request.AddFile("back", backImage.CopyTo, "back");
request.AddHeader("Content-Type", "multipart/form-data");

On my web service side, I accept the json as the argument to the method and manually obtain a reference to the file streams:

在我的Web服务端,我接受json作为方法的参数并手动获取对文件流的引用:

public JsonResult MyService(StoreImageRequest request)
{
    var frontImage = HttpContext.Request.Files["front"].InputStream;
    var backImage = HttpContext.Request.Files["front"].InputStream;
}

#2


-1  

If your server can process a multi-part with JSON body and Files parts, then:

如果您的服务器可以使用JSON正文和文件部分处理多部分,那么:

        var req = new RestRequest(UPLOAD_DOC_URLSEGMENT, Method.POST);

        req.RequestFormat = DataFormat.Json;
        req.AddBody(doc);

        req.AddFileBytes("TestImage", Properties.Resources.TestImage, "TestImage.jpg");

        req.AddHeader("apikey", "MY-API-KEY");
        var resp = restClient.Execute<ApiResult>(req);

At the server side such multi-part request should be processed as:

在服务器端,这样的多部分请求应该被处理为:

    [HttpPost]
    public JsonResult UploadDoc()
    {
        // This is multipart request. So we should get JSON from http form part:
        MyDocModel doc = JsonConvert.DeserializeObject<MyDocModel>(Request.Form[0]);

        foreach (string fileName in request.Files)
        {
            HttpPostedFileBase file = request.Files[fileName];
        }

#1


7  

So I am doing this by working around a problem with using the AddBody method which automatically kills the multi part form images and will not send them. You must use add parameter instead.

所以我通过解决使用AddBody方法的问题来做到这一点,该方法自动杀死多部分表单图像并且不会发送它们。您必须使用add参数。

To solve this problem you may have to do a little work on both sides of the communication.

要解决这个问题,您可能需要在通信的两个方面做一些工作。

To send the message from the client you do the following:

要从客户端发送消息,请执行以下操作:

new RestRequest("<Your URI>");
request.AddParameter("request", tokenRequest.ToJson());
request.AddFile("front", frontImage.CopyTo, "front");
request.AddFile("back", backImage.CopyTo, "back");
request.AddHeader("Content-Type", "multipart/form-data");

On my web service side, I accept the json as the argument to the method and manually obtain a reference to the file streams:

在我的Web服务端,我接受json作为方法的参数并手动获取对文件流的引用:

public JsonResult MyService(StoreImageRequest request)
{
    var frontImage = HttpContext.Request.Files["front"].InputStream;
    var backImage = HttpContext.Request.Files["front"].InputStream;
}

#2


-1  

If your server can process a multi-part with JSON body and Files parts, then:

如果您的服务器可以使用JSON正文和文件部分处理多部分,那么:

        var req = new RestRequest(UPLOAD_DOC_URLSEGMENT, Method.POST);

        req.RequestFormat = DataFormat.Json;
        req.AddBody(doc);

        req.AddFileBytes("TestImage", Properties.Resources.TestImage, "TestImage.jpg");

        req.AddHeader("apikey", "MY-API-KEY");
        var resp = restClient.Execute<ApiResult>(req);

At the server side such multi-part request should be processed as:

在服务器端,这样的多部分请求应该被处理为:

    [HttpPost]
    public JsonResult UploadDoc()
    {
        // This is multipart request. So we should get JSON from http form part:
        MyDocModel doc = JsonConvert.DeserializeObject<MyDocModel>(Request.Form[0]);

        foreach (string fileName in request.Files)
        {
            HttpPostedFileBase file = request.Files[fileName];
        }