我的单元测试有效,控制器中的相同代码不起作用

My UnitTest works, an identical code in the Controller does not work

这是我第一次 post 在这里,我是 C# 的新手。 我正在研究 Microsoft Cognitive API,(它从图像中提取信息),您发送 HTTP 请求,您会从 Microsoft 服务器获得回复。 - https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/tutorials/csharptutorial

这是我的单元测试(有效)

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;
using fw8.CognitiveServices;

namespace ImageTests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestImagefromURL()
        {
            Debug.WriteLine("Test was loaded");
            Manager instance = new Manager();
            var client = instance.StartMyTask().Result;
            Debug.WriteLine("Caption: " + client.Description.Captions[0].Text);
        }
    }
}

这个测试的输出是

Test Name:  TestImagefromURL
Test Outcome:   Passed
Result StandardOutput:  
Trace du débogage :
Test was loaded
Task started
processing
finish
Caption: a man holding a cat

在 class 库中调用这些方法

using System.Threading.Tasks;
using Microsoft.ProjectOxford.Vision.Contract;
using Microsoft.ProjectOxford.Vision;
using System.IO;
using System.Diagnostics;

namespace fw8.CognitiveServices
{
    public class Manager
    {
        public async Task<AnalysisResult> StartMyTask()
        {
            Debug.WriteLine("Task started");
            return await UploadAndAnalyzeImage(@"C:\Users\danie\Desktop\tot.jpg");//For testing purpose, a file from my computer
        }

        private static async Task<AnalysisResult> UploadAndAnalyzeImage(string imageFilePath)
        {
            Debug.WriteLine("processing");
            VisionServiceClient VisionServiceClient = new VisionServiceClient("APIKEY");

              using (Stream imageFileStream = File.OpenRead(imageFilePath))
            {
                VisualFeature[] visualFeatures = new VisualFeature[] { VisualFeature.Adult, VisualFeature.Categories, VisualFeature.Color, VisualFeature.Description, VisualFeature.Faces, VisualFeature.ImageType, VisualFeature.Tags };
                AnalysisResult analysisResult = await VisionServiceClient.AnalyzeImageAsync(imageFileStream, visualFeatures);
                Debug.WriteLine("finish");
                return analysisResult;
            }

        }
    }
}

现在从一个空白的 MVC 项目调用相同的方法

using fw8.CognitiveServices;
using System.Diagnostics;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public void Test()
        {

            Debug.WriteLine("Test was loaded");
            Manager instance = new Manager();
            var client = instance.StartMyTask().Result;
            Debug.WriteLine("Caption: " + client.Description.Captions[0].Text);
        }
    }
}

先谢谢能赐教的人了! ;)

编辑:哎呀

code:-32000
message:No script for id: 35
'iisexpress.exe' (CLR v4.0.30319: Domain 3): Unloaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'
'iisexpress.exe' (CLR v4.0.30319: AppInsightsDomain-0cd03d5b-6ce4-4019-ae7e-b1df44463c51): Unloaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll'
'iisexpress.exe' (CLR v4.0.30319: AppInsightsDomain-0cd03d5b-6ce4-4019-ae7e-b1df44463c51): Unloaded 'C:\Users\danie\AppData\Local\Temp\Temporary ASP.NET Files\vsf3c5b55cedeaf\assembly\dl3ecb1d3[=14=]2a8e73_afafd201\Microsoft.AI.WindowsServer.dll'
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Message","time":"2017-05-05T10:08:49.8412130Z","tags":{"ai.internal.sdkVersion":"dotnet:2.3.0-41907","ai.operation.id":"OxulrgX+fP0=","ai.location.ip":"127.0.0.1","ai.operation.syntheticSource":"SDKTelemetry","ai.cloud.roleInstance":"DESKTOP-TE2K4KD","ai.operation.name":"GET /","ai.operation.parentId":"OxulrgX+fP0="},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"AI: Diagnostic message: Performance counters are unavailable when the application is running under IIS Express. Use EnableIISExpressPerformanceCounters element with a value of 'true' within the Performance Collector Module element to override this behavior."}}}
Test was loaded
Task started
processing
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2017-05-05T10:08:51.1478126Z","tags":{"ai.internal.sdkVersion":"rddf:2.3.0-1223","ai.internal.nodeName":"DESKTOP-TE2K4KD","ai.operation.id":"F5d9uEXsrsw=","ai.location.ip":"::1","ai.cloud.roleInstance":"DESKTOP-TE2K4KD","ai.operation.name":"GET Home/Index","ai.operation.parentId":"F5d9uEXsrsw="},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"/vision/v1.0/analyze","id":"LikCUv5jYNQ=","data":"https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Adult,Categories,Color,Description,Faces,ImageType,Tags&subscription-key=d29a6dad583544d385357110f86d0ea4","duration":"00:00:04.4499171","resultCode":"200","success":true,"type":"Http","target":"westus.api.cognitive.microsoft.com","properties":{"DeveloperMode":"true"}}}}
The program '[17736] chrome.exe: WebKit' has exited with code -1 (0xffffffff).
The program '[5428] iisexpress.exe' has exited with code -1 (0xffffffff).

编辑 2:

不知道它是否非常微妙,但实际上当您同步而不是异步执行这些方法时它会起作用。

如果您正在调用 async 方法,您也应该将控制器方法设为 async。另外你的方法真的应该 return something...

例如

[HttpPost]
public async Task<ActionResult> Test()
{
    Debug.WriteLine("Test was loaded");
    Manager instance = new Manager();
    var client = await instance.StartMyTask();
    return Content("Caption: " + client.Description.Captions[0].Text);
}

如果使用 Task<>,您应该尝试始终使用异步,以避免 async/await 和 .Result.Wait() 等阻塞调用可能导致的情况陷入僵局。

测试可以转换为异步。

namespace ImageTests
{
    [TestClass]
    public class UnitTest1 {
        [TestMethod]
        public async Task TestImagefromURL() {
            Debug.WriteLine("Test was loaded");
            var instance = new Manager();
            var client = instance.StartMyTask();
            Debug.WriteLine("Caption: " + client.Description.Captions[0].Text);
        }
    }
}

并且Asp.Net MVC 在其框架内广泛使用异步任务。这意味着您的操作要么一直同步,要么一直异步。混合它们会产生不利影响。

public class HomeController : Controller {
    public ActionResult Index() {
        return View();
    }

    [HttpPost]
    public async Task<ActionResult> Test() {
        Debug.WriteLine("Test was loaded");
        var instance = new Manager();
        var client = await instance.StartMyTask();
        var msg = "Caption: " + client.Description.Captions[0].Text;
        Debug.WriteLine(msg);
        return Json(msg, JsonRequestBehavior.AllowGet);
    }
}