C# 加速webrequest代码

C# 加速webrequest代码,c#,performance,C#,Performance,我在下面的代码中遇到了一些性能问题,post请求大约需要1.5秒,我想知道是否还有其他方法可以用来加速这个过程?我尝试使用Proxy=null方法。可能是因为将数据解析为动态对象 public void loginWithUsernamePassword(string username, string password) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); WebClient n = n

我在下面的代码中遇到了一些性能问题,post请求大约需要1.5秒,我想知道是否还有其他方法可以用来加速这个过程?我尝试使用
Proxy=null方法。可能是因为将数据解析为动态对象

public void loginWithUsernamePassword(string username, string password)
{
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();

    WebClient n = new WebClient();
    object request = new { username = username, password = password };

    try
    {
        string data = JsonConvert.SerializeObject(request); 
        var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://192.168.201.10/api/v1/auth/login");

        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add("X-Api-Key", cocusAPI.Apikey);
        httpWebRequest.Method = "POST";
        httpWebRequest.Proxy = null;

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(data);
            streamWriter.Flush();
            streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            dynamic item = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
            if (item.data.success == true)
            {
                Consolelog("API loginWithUsername successfull");
                cocusAPI.Accesstoken = httpResponse.GetResponseHeader("X-Access-Token");
            }
            else
            {
                Consolelog("login failed"); 
            }
        }

        stopwatch.Stop();
        Console.WriteLine(stopwatch.Elapsed);
    }
    catch (WebException ex)
    {
        var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
        Consolelog(resp);
        Console.ReadKey();
    }
}

您是否尝试过使用代码以外的其他方式发布帖子?例如,Postman Chrome扩展。这将告诉你哪一方是慢的-服务器或客户端。如果你真的想知道慢在哪里,你可以在不同的位置添加Console.WriteLine(stopwatch.appeased)来找出它,或者使用Visual Studio中的性能工具。获取响应可能需要几秒钟的时间。如果您知道反序列化对象的类型,则无需使用
dynamic
。只需使用
反序列化对象(结果)
。当您使用
dynamic
时,您实际上是在调用(编译器的一个子集),如果您担心性能,这听起来不是一件好事。@KSib我意识到了这一点,做了更多的研究告诉我,如果(item.data.success==true)大约需要半秒钟,则只需反序列化Object30ms@ErwinVorenhout:是的,但反序列化对象并不是以任何方式“解释”(或编译)对象。当您访问一个属性时,对象的“动态”性质需要C#
dynamic
机制来确定对象具有哪些方法/属性。因此,再次尝试使用
反序列化对象
,如果可以的话。