The problem
I have an api GET method to retrieve site configuration. I am using httpClient
and the GetAsync()
method to do this.
HttpResponseMessage response = await client.GetAsync("api/{0}/config", id);
As I need this configuration across the site, I planned to use a global action filter for this.
Question
How can I call an async method in an MVC action filter? Or is there a better solution to this problem?
I have looked at multiple SO questions (Async action filter in MVC 4) on this but I not found a satisfactory solution.
STEP 01 Create new MVC Application project, named as "Async". In the File menu, click New Project. In the "New Project" dialog box, under Project types, expand Visual C#, and then click "Web". In the Name box, type "Async", then click on Ok.
1 Answer. Show activity on this post. It is best for you to use async/await down the whole call stack which is possible with MVC. Mark your Action as async and then use the await keyword to wait for the results from the CsvReader method.
Asynchronous actions are best when your method is I/O, network-bound, or long-running and parallelizable. Another benefit of an asynchronous action is that it can be more easily canceled by the user than a synchronous request.
The ASP.NET MVC framework supports four different types of filters: Authorization filters – Implements the IAuthorizationFilter attribute.
There is no way to (reliably) call an asynchronous method from an ASP.NET MVC 5 action filter. This has already been fixed in ASP.NET vNext, but AFAIK there are no plans to support this in MVC 5.
If you absolutely must do this in an action filter, then you must use synchronous calls (e.g., WebClient
instead of HttpClient
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With