You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS2015+WPF+C#环境下向HttpRequest上传文件

嘿,刚好我之前碰过类似的开发场景,给你整理了一套适配你需求的方案——用VS2015+WPF+C#调用同解决方案里的ASP.NET Web服务,还能搞定带文件的HttpRequest调用:

实现带文件上传的HttpRequest调用步骤

一、先确认Web服务端的接收能力

首先得确保你的Web服务方法支持接收文件,这里分两种常见的Web服务类型给你示例:

1. ASP.NET Web API 服务端方法

如果是Web API,用MultipartFormDataContent来处理上传是最方便的:

using System.Web.Http;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;

public class TestWebServiceController : ApiController
{
    [HttpPost]
    public async Task<IHttpActionResult> UploadFileWithParams()
    {
        // 校验请求格式
        if (!Request.Content.IsMimeMultipartContent())
        {
            return BadRequest("请求需为multipart/form-data格式");
        }

        // 设置文件存储路径(记得给这个目录加写入权限)
        string uploadDir = HttpContext.Current.Server.MapPath("~/Uploads");
        if (!Directory.Exists(uploadDir)) Directory.CreateDirectory(uploadDir);

        // 解析请求内容
        var streamProvider = new MultipartFormDataStreamProvider(uploadDir);
        await Request.Content.ReadAsMultipartAsync(streamProvider);

        // 获取URL参数/表单参数
        string testParam = streamProvider.FormData.GetValues("testParam")?.FirstOrDefault();

        // 处理上传的文件
        foreach (var fileData in streamProvider.FileData)
        {
            string originalFileName = fileData.Headers.ContentDisposition.FileName.Trim('"');
            string savedPath = Path.Combine(uploadDir, originalFileName);
            // 如果需要重命名可以在这里处理
            File.Move(fileData.LocalFileName, savedPath);
        }

        return Ok("文件上传完成,参数已接收");
    }
}

2. 传统ASMX Web服务端方法

如果是老的ASMX服务,直接通过HttpContext读取上传文件:

using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestService : WebService
{
    [WebMethod]
    public string UploadFile()
    {
        HttpPostedFile uploadedFile = HttpContext.Current.Request.Files["uploadedFile"];
        if (uploadedFile != null && uploadedFile.ContentLength > 0)
        {
            string savePath = Server.MapPath("~/Uploads/" + uploadedFile.FileName);
            uploadedFile.SaveAs(savePath);
            // 读取其他参数
            string paramValue = HttpContext.Current.Request.Form["testParam"];
            return $"文件{uploadedFile.FileName}上传成功,参数值:{paramValue}";
        }
        return "未检测到有效上传文件";
    }
}

二、WPF客户端的HttpRequest实现

在你的WPF测试应用里,用HttpClient来构建带文件的请求(比传统HttpWebRequest更简洁):

using System.Net.Http;
using System.IO;
using System.Windows;

private async void UploadButton_Click(object sender, RoutedEventArgs e)
{
    // 替换成你的Web服务地址(同解决方案的话,调试时用Web服务的本地端口)
    string serviceUrl = "http://localhost:58792/api/TestWebService/UploadFileWithParams";
    string filePath = @"C:\Users\YourName\Desktop\test.pdf"; // 要上传的文件路径
    string testParam = "调试测试参数";

    try
    {
        using (HttpClient client = new HttpClient())
        using (MultipartFormDataContent formContent = new MultipartFormDataContent())
        {
            // 添加普通参数
            formContent.Add(new StringContent(testParam), "testParam");

            // 添加文件内容
            using (FileStream fileStream = File.OpenRead(filePath))
            {
                StreamContent fileContent = new StreamContent(fileStream);
                // 设置文件的Content-Type,根据实际文件类型调整,比如image/png、application/json等
                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                // 第三个参数是服务端接收的文件名
                formContent.Add(fileContent, "uploadedFile", Path.GetFileName(filePath));
            }

            // 发送POST请求
            HttpResponseMessage response = await client.PostAsync(serviceUrl, formContent);

            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                MessageBox.Show($"调用成功:{result}", "提示");
            }
            else
            {
                MessageBox.Show($"调用失败,状态码:{response.StatusCode}", "错误");
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"发生异常:{ex.Message}", "错误");
    }
}

三、调试注意事项

  • 确保Web服务项目和WPF测试项目在同一个解决方案里,调试时可以设置多启动项目,让两者同时运行,避免手动启动服务的麻烦。
  • 给Web服务的Uploads目录添加写入权限,否则会出现文件保存失败的错误。
  • 如果用WPF的UI按钮触发,记得用async/await,别阻塞UI线程。
  • 可以用Fiddler抓包查看请求结构,确认文件和参数是否正确发送到服务端。

内容的提问来源于stack exchange,提问作者Patrick Pirzer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:05:59