亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法在 ASP.NET MVC 中捕獲異常

無法在 ASP.NET MVC 中捕獲異常

C#
烙印99 2021-07-09 14:00:19
我目前正在嘗試為我的 IoT 學校項目開發簡單的 Web 應用程序。至于現在它應該只從我的 Raspberry 調用直接方法。我正在為 C# 使用 Azure SDK。這是代碼的樣子:控制器:    public ActionResult changeState(int? id, bool enable)    {        string conn_str = (from u in db.Users join h in db.Hubs on                u.Hub.HubId equals h.HubId                where u.UserName == User.Identity.Name select h.connection_str).First();        Cloud2Device c2d = new Cloud2Device(conn_str);        if (id == null)        {            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);        }        Rp rp = db.Rps.SingleOrDefault(r => r.RpId == id);        if (rp == null)        {            return HttpNotFound();        }        //IoT stuff        try        {           c2d.EnableRaspberry("myDeviceId").Wait();        }        catch(Exception ex)        {           //do something        }        rp.is_enabled = enable;        db.SaveChanges();        return RedirectToAction("Index");    }物聯網應用:public class Cloud2Device{    private ServiceClient s_serviceClient;    public Cloud2Device(string conn_str)    {        s_serviceClient = ServiceClient.CreateFromConnectionString(conn_str);    }    public async Task EnableRaspberry(string deviceId)    {        var methodInvocation = new CloudToDeviceMethod("EnableRaspberry") { ResponseTimeout = TimeSpan.FromSeconds(2) };         var response = await s_serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation);        Debug.WriteLine(response.GetPayloadAsJson());    }}問題是,從調試輸出中我可以看到異常 Microsoft.Azure.Devices.Common.Exceptions.DeviceNotFoundException 被拋出,但是它沒有被 try-catch 塊處理。
查看完整描述

1 回答

?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

我不確定錯誤輸出實際上是向您的代碼拋出的異常。它可能是 ApplicationInsights 只是記錄。 但是,我認為由于調用Wait和阻止了異步方法的返回,代碼被凍結了。

使控制器方法返回 type Task<ActionResult>,使該方法async,然后用于await c2d.EnableRaspberry("myDeviceId");調用該方法。

看看這樣做是否會導致異常(或成功)。


查看完整回答
反對 回復 2021-07-10
  • 1 回答
  • 0 關注
  • 160 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號