如何从 C# 中刷新 spark 核心

How to flash a spark core from C#

我正在尝试从 C# 应用程序中刷新 spark 核心。我不断收到 { error: Nothing to do? } 回复。

下面是我的代码

var url = string.Format("https://api.spark.io/v1/devices/{0}", sparkDeviceID);

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accesstoken);
    using (var formData = new MultipartFormDataContent())
    {
        HttpContent fileContent = new ByteArrayContent(Encoding.ASCII.GetBytes(rom));
        //client.SendAsync()
        formData.Add(fileContent, "file", "file");
        var response = client.PutAsync(url, formData).Result;

        if (!response.IsSuccessStatusCode)
            throw new Exception("An error occurred during rom flash!");

        var responseStream = response.Content.ReadAsStreamAsync().Result;
        using (var reader = new StreamReader(responseStream, true))
        {
            var result = reader.ReadToEnd();
        }
    }
    return true;
}

文档内容如下:

The API request should be encoded as multipart/form-data with a file field populated.

我认为问题是端点看不到该文件。知道如何解决这个问题吗?

终于成功了。

问题在于 .NET 为文件表单数据生成 content-disposition header 的方式。

我使用 fiddler 将成功放置请求的输出与我的代码生成的放置请求进行比较:

使用 CURL 生成成功的 PUT 请求:

PUT http://127.0.0.1:8888/ HTTP/1.1
User-Agent: curl/7.33.0
Host: 127.0.0.1:8888
Accept: */*
Content-Length: 2861
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------5efcf64a370f13c8

--------------------------5efcf64a370f13c8
Content-Disposition: form-data; name="file"; filename="ms.ino"
Content-Type: application/octet-stream

...

我的PUT请求(未成功):

PUT https://api.spark.io/v1/devices/{deviceid} HTTP/1.1
Authorization: Bearer {access_token}
Content-Type: multipart/form-data; boundary="135f5425-9342-4ffa-a645-99c04834026f"
Host: api.spark.io
Content-Length: 2878
Expect: 100-continue

--135f5425-9342-4ffa-a645-99c04834026f
Content-Type: application/octet-stream
Content-Disposition: form-data; name=file; filename=file.ino; filename*=utf-8''file.ino

...

如果您注意到发送的实际文件的 Content-Type 不同:

成功:Content-Disposition:form-data;姓名="file";文件名="ms.ino"

不成功:Content-Disposition:form-data;名称=文件;文件名=file.ino;文件名*=utf-8''file.ino

最具体地说,解决方案是在 name 属性周围添加引号。

解析:

formData.Add(fileContent, "\"file\"", "file.ino");