Оригинальная проблема решена, поэтому поделиться для других:
.NET Core v2.0 (создан для работы в качестве AWS Lambda), но не ограничивается этим.
Существует некоторая гибкость в реализации; написано для (надеюсь) простоты чтения.
Моя конечная цель - загрузить файл kml (или другой файл) из облака в Mapbox через Lambda. В настоящее время локально тестирую консольное приложение C #, пытаясь переместить только локальный файл.
Я следовал документации API от Mapbox , и (с настройками) получил отдельную версию cURL для нормальной работы. Я использовал рабочую версию cURL, документацию и собственные вопросы другого пользователя SO 1 & 2 относительно этой темы в качестве руководства.
namespace MapboxTilesetUploader
{
class Function
{
public static string mbxUsername = "{your-mapbox-username}";
public static string mbxAccessToken = "{your-mapbox-secret-token}";
public static string file = "{filepath-to-your-file}";
public static string htmlFile = "{location-of-your-file}";
public static void Main()
{
Mapbox mapbox = new Mapbox(mbxUsername, mbxAccessToken);
mapbox.GetS3Credentials();
// If getting file from a local source
mapbox.StageFileToS3(file);
// If getting file from a non-local source
// Stream stream = Mapbox.GetStreamFromUrl(htmlFile);
// var responseStageFileToS3 = mapbox.StageFileToS3Async(stream).Result;
/* forces the response to finish, otherwise no upload to Mapbox will occur */
var responseString = mapbox.UploadS3FileToMapboxAsync("my-tileset", "file-title").Result;
}
}
class Mapbox
{
private string m_mbxUsername;
private string m_mbxAccessToken;
private string m_mbxApiCredentialsUri;
private string m_mbxApiUploadUri;
private static readonly HttpClient client = new HttpClient();
public Mapbox(string mbxUsername, string mbxAccessToken)
{
m_mbxUsername = mbxUsername;
m_mbxAccessToken = mbxAccessToken;
m_mbxApiCredentialsUri = "https://api.mapbox.com/uploads/v1/" + mbxUsername + "/credentials?access_token=" + mbxAccessToken;
m_mbxApiUploadUri = "https://api.mapbox.com/uploads/v1/" + mbxUsername + "?access_token=" + mbxAccessToken;
}
public void GetS3Credentials()
{
/* https: //api.mapbox.com/uploads/v1/{mbxUsername}/credentials?access_token={mbxAccessToken} */
var request = (System.Net.HttpWebRequest)WebRequest.Create(m_mbxApiCredentialsUri);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
var result = reader.ReadToEnd();
var mapboxS3Credentials = JObject.Parse(result);
MapboxS3Credentials.accessKeyId = (string)mapboxS3Credentials["accessKeyId"];
MapboxS3Credentials.bucket = (string)mapboxS3Credentials["bucket"];
MapboxS3Credentials.key = (string)mapboxS3Credentials["key"];
MapboxS3Credentials.secretAccessKey = (string)mapboxS3Credentials["secretAccessKey"];
MapboxS3Credentials.sessionToken = (string)mapboxS3Credentials["sessionToken"];
MapboxS3Credentials.url = (string)mapboxS3Credentials["url"];
}
}
}
}
}
public void StageFileToS3(string filepath)
{
var s3client = new AmazonS3Client(
MapboxS3Credentials.accessKeyId,
MapboxS3Credentials.secretAccessKey,
MapboxS3Credentials.sessionToken,
Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = MapboxS3Credentials.bucket,
Key = MapboxS3Credentials.key,
FilePath = filepath,
ContentType = "text/plain"
};
PutObjectResponse response = s3client.PutObjectAsync(putRequest).Result;
}
catch (AmazonS3Exception amazonS3Exception)
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
// If getting file from a stream
public static MemoryStream GetStreamFromUrl(string url)
{
byte[] streamBytes = null;
MemoryStream streamData = null;
try
{
using (var webClient = new WebClient())
{
streamBytes = webClient.DownloadData(url);
}
streamData = new MemoryStream(streamBytes);
}
catch (Exception ex)
{
Console.WriteLine("Exception getting stream from url: " + ex);
}
return streamData;
}
// If getting file from a stream
public async Task<PutObjectResponse> StageFileToS3Async(Stream stream)
{
var s3client = new AmazonS3Client(
MapboxS3Credentials.accessKeyId,
MapboxS3Credentials.secretAccessKey,
MapboxS3Credentials.sessionToken,
Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = MapboxS3Credentials.bucket,
Key = MapboxS3Credentials.key,
InputStream = stream,
};
PutObjectResponse response = await s3client.PutObjectAsync(putRequest);
return response;
}
catch (AmazonS3Exception amazonS3Exception)
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
public async Task<HttpResponseMessage> UploadS3FileToMapboxAsync(string setTilesetName, string setCustomName = null)
{
/*
"tileset": "username.custom-tileset-name",
"url": "https://{bucket}.s3.amazonaws.com/{key}",
"name": "{custom-name}"
*/
Dictionary<string, string> content = new Dictionary<string, string>() {
{ "tileset", m_mbxUsername + "." + setTilesetName },
{ "url", "https://" + MapboxS3Credentials.bucket + ".s3.amazonaws.com/" + MapboxS3Credentials.key },
{ "name", setCustomName } };
var encodedContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
var response = await client.PostAsync(m_mbxApiUploadUri, encodedContent);
return response;
}
static class MapboxS3Credentials
{
public static string accessKeyId;
public static string bucket;
public static string key;
public static string secretAccessKey;
public static string sessionToken;
public static string url;
}
}