asp.net - 如果设置 ContentLength>0 或 SendChunked==true,则必须提供请求正文。通过在 [Begin]GetResponse 之前调用 [Begin]GetRequestStream 来执行此操作
问题描述
我尝试在 oracle 云基础架构 iaas 上上传文件,但出现错误。我不确定我附加在正文中的文件格式是否正确。ApI 签名是正确的,我只是怀疑我编写的代码是否符合要求。代码片段如下所述。代码片段:
FileInfo f = new FileInfo(FileUpload1.FileName);
byte[] filebyte =FileUpload1.FileBytes;
var postdata = Encoding.UTF8.GetBytes(filebyte.ToString());
Console.Write(postdata.Length);
var tenancyId = ConfigurationManager.AppSettings["BMCTenancyId"];
var userId = ConfigurationManager.AppSettings["BMCUserId"];
var fingerprint = ConfigurationManager.AppSettings["BMCFingerprint"];
var privateKeyPath = ConfigurationManager.AppSettings["BMCPrivateKeyPath"];
var privateKeyPassphrase = ConfigurationManager.AppSettings["BMCPrivateKeyPassphrase"];
var signer = new RequestSigner(tenancyId, userId, fingerprint, privateKeyPath, privateKeyPassphrase);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.SendChunked = true;
request.ContentType = "text/plain";
request.ContentLength =postdata.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(postdata, 0, postdata.Length);
stream.Close();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
request.Headers["x-content-sha256"] = Convert.ToBase64String(SHA256.Create().ComputeHash(postdata));
signer.SignRequest(request);
Console.WriteLine($"Authorization header: {request.Headers["authorization"]}");
ExecuteRequest(request);
Console.WriteLine("The value of 'ContentLength' property after sending the data is {0}", request.ContentLength);
}
private static void ExecuteRequest(HttpWebRequest request)
{
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
var response = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
Console.WriteLine($"Response: {response}");
}
catch (WebException e)
{
Console.WriteLine($"Exception occurred: {e.Message}");
Console.WriteLine($"Response: {new StreamReader(e.Response.GetResponseStream()).ReadToEnd()}");
}
}
解决方案
一方面,您需要将 URL 更新为以下格式:
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/n/{namespaceName}/b/{bucketName}/o/{objectName}");
文档:https ://docs.cloud.oracle.com/iaas/api/#/en/objectstorage/20160918/Object/PutObject
另外,您能否编辑问题以包含您收到的完整错误,这将有助于调试。
推荐阅读
- c# - 如何在 C# 中将文件枚举到只有 3 个文件目录?
- json - 使用 discord.py 将已经存在的 json 文件作为嵌入发送
- reactjs - react-router - 与字符串形式的链接有效,但不是对象形式
- javascript - 未捕获的类型错误:无法读取 null 的属性“dispatchEvent”。不知道发生了什么
- flutter - 如何在 Flutter 中连续创建 2 个按钮?
- docker - 容器启动时在 docker 映像内创建多个用户
- message-queue - 您如何处理有期限的消息
- c# - 使用 ManagmentObjectSearcher 的 C# wmi 查询异常无效类
- rust - 如何在匹配中处理 Rust 中的错误?
- c# - 突出显示 RichTextBox 控件中的文本