【问题标题】:Exception occurred during a WebClient requestWebClient 请求期间发生异常
【发布时间】:2016-05-09 11:56:32
【问题描述】:

WinForm 应用程序代码-

FileSystemWatcher fsWatcher = new FileSystemWatcher();
fsWatcher.Created += new FileSystemEventHandler(OnCreated);

    public void OnCreated(object sender, FileSystemEventArgs e)
    {
        try
        {
            var wc = new WebClient();

            byte[] response = 
                    wc.UploadFile("http://localhost:54802/Home/ReceiveAudio/", 
                                  "POST", e.FullPath);
            string s = System.Text.Encoding.ASCII.GetString(response);
            MessageBox.Show(s);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

MVC 控制器动作方法-

    [HttpPost]
    public JsonResult ReceiveAudio()
    {
        return Json("Success", JsonRequestBehavior.AllowGet);
    }

我收到错误 -An exception occurred during a WebClient request.

有什么帮助吗?

【问题讨论】:

  • 你为什么在 post 请求中使用JsonRequestBehavior.AllowGet

标签: c# asp.net-mvc winforms file-upload webclient


【解决方案1】:

在windows侧:

private void uploadButton_Click(object sender, EventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    var dialogResult = openFileDialog.ShowDialog();    
    if (dialogResult != DialogResult.OK) return;              
    Upload(openFileDialog.FileName);
}

private void Upload(string fileName)
{
    var client = new WebClient();
    var uri = new Uri("https://www.yoursite.com/UploadFile/");  
    try
    {
        client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
        var data = System.IO.File.ReadAllBytes(fileName);
        client.UploadDataAsync(uri, data);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

在服务器端你应该使用 WebApi:

[HttpPost]
public async Task<object> UploadFile()
{
    var file = await Request.Content.ReadAsByteArrayAsync();
    var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
    var filePath = "/upload/files/";
    try
    {
        File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);           
    }
    catch (Exception ex)
    {
        // ignored
    }

    return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多