我是否应该检查 WebClient.UploadFile 的响应以了解上传是否成功? [英] Should I check the response of WebClient.UploadFile to know if the upload was successful?

查看:74
本文介绍了我是否应该检查 WebClient.UploadFile 的响应以了解上传是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未使用过 WebClient,我不确定是否应该检查服务器的响应以了解上传是否成功,或者如果没有异常,我是否可以让文件上传.

I never used the WebClient before and I'm not sure if I should check the response from the server to know if the upload was successful or if I can let the file as uploaded if there is no exception.

如果我应该检查响应,我该怎么做?解析 resposeHeaders 属性?

If I should check the response how can I do that? Parsing resposeHeaders property?

提前致谢.

推荐答案

UploadFile 方法返回一个 byte[],其中包含远程服务器返回的响应.根据服务器如何管理上传请求的响应(和错误条件(参见下面的注释 1)),您将需要检查该响应.您可以通过将其转换为字符串来获取字符串响应,例如这会将响应写入控制台窗口:

The UploadFile method returns a byte[] that contains the response the remote server returned. Depending on how the server manages responses to upload requests (and error conditions (see note 1 below)) you will need to check that response. You can get the string response by converting it to a string, for example this will write the response to the console window:

byte[] rawResponse = webClient.UploadFile(url,fileName);
Console.WriteLine("Remote Response: {0}", System.Text.Encoding.ASCII.GetString(rawResponse));

也就是说,如果远程服务器返回 HTTP 200 以外的任何内容(即成功),则对 UploadFile 的调用将引发 WebException.您可以以最适合您的应用程序的方式捕获并处理它.

That said if the remote server returns anything other than a HTTP 200 (i.e. success) the call to UploadFile will throw a WebException. This you can catch and deal with it whatever manner best suits your application.

把所有这些放在一起

try
{
    WebClient webClient = new WebClient();
    byte[] rawResponse = webClient.UploadFile(url,fileName);

    string response = System.Text.Encoding.ASCII.GetString(rawResponse);

    ...
    Your response validation code
    ...
}
catch (WebException wexc)
{
    ...
    Handle Web Exception
    ...
}

注意 1 举个例子,我有一个文件上传服务,除了 HTTP 200 代码之外,它永远不会发出任何东西,所有错误都在服务中被捕获,这些错误被解析"成一个 XML 结构返回给调用者.然后调用者解析该 XML 以验证上传是否成功.

Note 1 As an example I have a file upload service that will never issue anything other than a HTTP 200 code, all errors are caught within the service and these are "parsed" into an XML structure that is returned to the caller. The caller then parses that XML to validate that the upload was successful.

这篇关于我是否应该检查 WebClient.UploadFile 的响应以了解上传是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆