客户正在使用IBM的Watson Dialog服务,我找不到任何人使用.Net(特别是c#)做最基本的事情的例子。
IBM仅显示使用Curl,Node和Java的示例......
我的第一个目标是能够向watson服务添加新的xml文件(对话框树)。看起来很简单,但我现在已经打了一会儿。
答案 0 :(得分:3)
所以我最终通过拼凑相关主题的十几个谷歌搜索的帮助来完成这项工作。以为我会在这里发布工作版本。
下面是我的代码,它将使用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;
}
}