クライアントは IBM の Watson ダイアログ サービスを使用していますが、.Net (具体的には c#) を使用して最も基本的なことを行っている例を見つけることができません。
IBM は、Curl、Node、および Java を使用した例のみを示しています...
私の最初の目標は、新しい xml ファイル (ダイアログ ツリー) を watson サービスに追加できるようにすることです。単純に思えますが、私はしばらく頭を悩ませてきました。
クライアントは IBM の Watson ダイアログ サービスを使用していますが、.Net (具体的には c#) を使用して最も基本的なことを行っている例を見つけることができません。
IBM は、Curl、Node、および Java を使用した例のみを示しています...
私の最初の目標は、新しい xml ファイル (ダイアログ ツリー) を watson サービスに追加できるようにすることです。単純に思えますが、私はしばらく頭を悩ませてきました。
そこで、関連するトピックに関する約 10 の Google 検索の助けを借りて、最終的にこれを機能させることができました。ここに作業バージョンを投稿すると思いました。
以下は、MVC コントローラーで C# を使用して xml ファイルを Watson Dialog サービスにアップロードするコードです。
フロント エンドは、フレンドリ名 (.xml ファイル名に変換) とファイル自体のアップロード (dropzone を使用) を取るフォームです。
最適化があると確信していますが、これが誰かの役に立てば幸いです。幸いなことに、これはほぼすべての Watson Dialog サービス呼び出し (追加、更新、削除) を行うための基盤として使用できます。
public ContentResult Save(FormCollection form)
{
try
{
var name = form["txtDialogName"];
var filename = name + ".xml";
byte[] bytes = null;
foreach (string s in Request.Files)
{
var file = Request.Files[s];
using (Stream inputStream = file.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
bytes = memoryStream.ToArray();
}
break;
}
if (bytes == null)
{
var contentResult = new ContentResult
{
ContentType = "application/json",
Content = null
};
return contentResult;
}
var basePath = ConfigurationManager.AppSettings["WatsonPath"];
var username = ConfigurationManager.AppSettings["WatsonUsername"];
var password = ConfigurationManager.AppSettings["WatsonPassword"];
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password)));
var values = new[]
{ new KeyValuePair<string, string>("name", filename) };
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
foreach (var keyValuePair in values)
{
formData.Add(new StringContent(keyValuePair.Value), string.Format("\"{0}\"", keyValuePair.Key));
}
formData.Add(new ByteArrayContent(bytes),
'"' + "file" + '"',
'"' + filename + '"');
var response = client.PostAsync(basePath + "/v1/dialogs", formData).Result;
var result = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
var contentResult = new ContentResult
{
ContentType = "application/json",
Content = response.ReasonPhrase
};
return contentResult;
}
var successResult = new ContentResult
{
ContentType = "application/json",
Content = result
};
return successResult;
}
}
catch (Exception ex)
{
HandleError(ex);
var contentResult = new ContentResult
{
ContentType = "application/json",
Content = "false"
};
return contentResult;
}
}