WebClient - UploadValues:获取状态响应

WebClient - UploadValues : Get Status Response

我正在尝试将值从一个控制器传递到另一个域中的另一个控制器。我正在将数据添加到 NameValueCollection 并将其传递给另一个控制器 [httppost] 方法并在那里接收数据映射到与我传递的模型相同的模型。

目前我在本地 运行 通过同时打开两个 VS 实例。当两个 VS 打开时,值被正确传递并且信息被正确写入数据库,我收到类似 "{byte[0]}" 的响应。现在,当我尝试停止目标控制器项目并尝试提交数据时,它无法正常工作,但我仍然得到与 "{byte[0]}" 相同的响应。有人可以帮我在这种情况下如何 return 响应命令吗?有没有办法了解 UploadValues 已完成或未完成。

.........
.........

NameValueCollection resumeDetails = new NameValueCollection(); 
resumeDetails.Add("FirstName", "KRIZTE");

byte[] res = this.Post(ConfigurationManager.AppSettings["RedirectionUrl"].ToString(), resumeDetails);

return View("Index");
}

public byte[] Post(string uri, NameValueCollection resumeDetails)
{
    byte[] response = null;
    WebClient client = new WebClient();
    response = client.UploadValues(uri, resumeDetails);
    return response;
}

你不应该使用 WebClient 因为这样的问题。

Microsoft 将 HttpClient class 作为较新的 API 实施,它具有以下优点:

HttpClient is the newer of the APIs and it has the benefits of

has a good async programming model

1- being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard, e.g. generating standards-compliant headers

2- is in the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future

3- also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc.

所以我将向您展示一个使用 HttpClient:

的示例
var uri = "http://google.com";
        
var client = new HttpClient();
try
{
   var values = new List<KeyValuePair<string, string>>();

   // add values to data for post
   values.Add(new KeyValuePair<string, string>("FirstName", "KRITZTE"));
   FormUrlEncodedContent content = new FormUrlEncodedContent(values);

   // Post data
   var result = await client.PostAsync(uri, content);

   // Access content as stream which you can read into some string
   Console.WriteLine(result.Content);

   // Access the result status code
   Console.WriteLine(result.StatusCode);
}
catch(AggregateException ex)
{
    // get all possible exceptions which are thrown
    foreach (var item in ex.Flatten().InnerExceptions)
    {
        Console.WriteLine(item.Message);
    }
}