简体   繁体   中英

Microsoft Translator API work using console but not working within MVC

I have been able to get the Microsoft Translator API to work with creating a console project. I could only find examples with using console projects.

When trying to get the Translator API working within a controller I am not having any luck. I am using the same code.

Do I need to add some other type of reference to get the Translator to work with in MVC?

public async Task<string> GetAuthenticationToken(string key)

{
  string endpoint = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";

 using (var client = new HttpClient())
 {
    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "xxxxxxxxxxxxxxx501b7b1ce");
    var response = await client.PostAsync(endpoint, null);
    var token = await response.Content.ReadAsStringAsync();
    return token;
  }
}

Error Message

Is there any particular reason you have to create the console application first and then run it as such?

Instead of running the executable from your MVC project, I would recommend calling the TranslatorAsync() function instead.

My guess would be that the process.Start() and process.Close() calls are killing the process before it has a chance to do anything. However, without more specifics on how the function is failing, it's hard to give a better answer.

I had to change

TranslateAsync(productTest, getUserName).Wait;

to

await TranslateAsync(productTest, getUserName);

It's working now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM