我正在尝试上传文件以跟踪此服务中的API信息。 Easy Post API。
我能够使用摘要式身份验证成功发送第一个GET请求。
我在尝试使用“ PUT ”上传文件时收到403 - 未经授权。
这是我的代码。我正在使用自定义Web客户端在Web请求中设置参数。
public class CustomWebClient : WebClient
{
private BingMailConfigOptions ConfigOptions;
public CustomWebClient(BingMailConfigOptions configOptions) : base()
{
ConfigOptions = configOptions;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.ServicePoint.Expect100Continue = false;
request.Method = "PUT";
request.Credentials = GetCredentialCache(address, ConfigOptions);
return request;
}
public static CredentialCache GetCredentialCache(Uri uri, BingMailConfigOptions options)
{
var credentialCache = new CredentialCache
{
{
new Uri(uri.GetLeftPart(UriPartial.Authority)),
"Digest",
new NetworkCredential(options.AuthUserName, options.AuthPassword, uri.GetLeftPart(UriPartial.Authority))
}
};
return credentialCache;
}
}
// in a separate class.
private void Upload(string sessionId, string filePath)
{
_log.Trace("Trying to upload the file: " + filePath);
var file = new FileInfo(filePath);
if (file.Exists)
{
using (var uploader = new CustomWebClient(ConfigOptions))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
Uri uri = new Uri("https://bingmail.com.au/" + "direct_upload/{0}/{1}"(sessionId, HttpUtility.UrlEncode(file.Name)));
uploader.UploadFile(uri, "PUT", filePath);
}
}
else
{
throw new Exception("File Not found");
}
}
你能告诉我我做错了什么或者指出了我正确的方向吗?
由于
答案 0 :(得分:1)
我终于找到了解决方案。希望有一天能帮助别人。
除了一些易于弄清楚的方法之外的完整解决方案发布在这个要点中。 Bing-Mail Easy Post Api - Version 1.3
我所做的是从https://stackoverflow.com/a/3117042/959245修改DigestAuthFixer
以支持任何HTTP方法。
然后使用它创建会话,当我们使用DigestAuthFixer
创建会话时,它存储Digest-Auth标头,我可以在上传文件时重复使用。
using (var client = new WebClient())
{
var uri = new Uri(_easypostHosts[2] + UploadUri.FormatWith(sessionId, HttpUtility.UrlEncode(fileName)));
// get the auth headers which are already stored when we create the session
var digestHeader = DigestAuthFixer.GetDigestHeader(uri.PathAndQuery, "PUT");
// add the auth header to our web client
client.Headers.Add("Authorization", digestHeader);
// trying to use the UploadFile() method doesn't work in this case. so we get the bytes and upload data directly
byte[] fileBytes = File.ReadAllBytes(filePath);
// as a PUT request
var result = client.UploadData(uri, "PUT", fileBytes);
// result is also a byte[].
content = result.Length.ToString();
}