我有两个MVC网站。站点1的控制器使用以下代码调用站点2
// If I remove this in the controller of site1, then execution continues.... var asdf = SharedTypes.Utilities.GetjsonStream("http://localhost:11541/UIDP/Details/a1?format=json"); string g = asdf.Result; public class Utilities { public static async Task<string> GetjsonStream(string url) { HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); string content = await response.Content.ReadAsStringAsync(); Debug.WriteLine("Content: " + content); return content; } }
我可以直接浏览URL并查看JSON。但是从MVC中的对等网站下载JSON的正确方法是什么?
你或许应该把控制器方法为async方法和用途await,以避免死锁。
async
await
public async Task<ActionResult> MyActionAsync() { var asdf = SharedTypes.Utilities.GetjsonStream(someUrl); string g = await asdf; // return something }
Microsoft的ASP.NET教程包括有关ASP.NET MVC 4中异步方法的页面。