I'm trying to encapsulate some features in my application, for example instead of writing these codes in every POST action method:
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")
I have made something like this using extension method and custom actionresult:
return RedirectToAction("TicketList", "Ticket").WithSendNotification("notificationHub", "sendNotification");
In order to do that I've created a custom action result and I put the logic inside ExecuteResult
method:
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);
}
But I get following error:
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.
Now my question is that Can void async
method be used in custom action result?
Update: ASP.NET 5 has this ability, Means action result now have ActionResult.ExecuteResultAsync in addition to ActionResult.ExecuteResult
. Now I want to know How can we implement this ability in MVC 5.0?