我想封裝在我的應用程序的一些功能,例如而不是每一個崗位的操作方法編寫這些代碼:使用擴展方法和自定義的ActionResult可以在自定義ActionResult中使用void異步方法嗎?
var baseUrl = context.HttpContext.Request.Url.Scheme + "://" + context.HttpContext.Request.Url.Authority +
context.HttpContext.Request.ApplicationPath.TrimEnd('/') + "/signalr";
var hubConnection = new HubConnection(baseUrl);
var notification = hubConnection.CreateHubProxy(hubName: HubName);
await hubConnection.Start();
await notification.Invoke(MethodName);
return RedirectToAction("TicketList", "Ticket")
我做了這樣的事情:
return RedirectToAction("TicketList", "Ticket").WithSendNotification("notificationHub", "sendNotification");
爲了做到這一點我創建了一個自定義操作的結果,我把邏輯裏面ExecuteResult
方法:
public async override void ExecuteResult(ControllerContext context)
{
var baseUrl = context.HttpContext.Request.Url.Scheme + "://" + context.HttpContext.Request.Url.Authority +
context.HttpContext.Request.ApplicationPath.TrimEnd('/') + "/signalr";
var hubConnection = new HubConnection(baseUrl);
var notification = hubConnection.CreateHubProxy(hubName: HubName);
await hubConnection.Start();
await notification.Invoke(MethodName);
InnerResult.ExecuteResult(context);
}
但我得到以下錯誤:
An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.
現在我的問題是,能否void async
方法中的自定義操作的結果可以用嗎?
更新:ASP.NET 5有此能力,意思是除ActionResult.ExecuteResult
之外的動作結果現在有ActionResult.ExecuteResultAsync。現在我想知道我們如何在MVC 5.0中實現這個功能?
不是很清楚你爲什麼不想在控制器中重構方法......但是這裏有很長的問題和答案,爲什麼你真的不應該這樣做(包括像你一樣做火和忘記/崩潰的方式試圖做) - http://stackoverflow.com/questions/17659603/async-void-asp-net-and-count-of-outstanding-operations –