要在C#中创建一个Web服务,可以使用ASP.NET Web API或WCF(Windows Communication Foundation)。以下是使用ASP.NET Web API在C#中创建一个Web服务来传递文件给服务器处理的步骤:

  1. 创建一个新的ASP.NET Web API项目。
  2. 在项目中创建一个名为"FileController"的控制器。
  3. 在控制器中添加一个POST方法,用于接收文件并将其传递给服务器处理。例如:
public class FileController : ApiController
{
    [HttpPost]
    public async Task<IHttpActionResult> UploadFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            return BadRequest("Invalid request");
        }

        var provider = new MultipartFormDataStreamProvider("<服务器文件存储路径>");

        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);

            // 处理文件
            foreach (var file in provider.FileData)
            {
                string filePath = file.LocalFileName;
                // 进行文件处理操作
            }

            return Ok("File(s) uploaded successfully");
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }
}
  1. 在Web.config文件中添加以下配置,以允许文件上传:
<system.web>
  <httpRuntime targetFramework="4.7.2" maxRequestLength="1048576" />
</system.web>
<system.webServer>
  <security>
    <requestFiltering>
      <requestLimits maxAllowedContentLength="1048576" />
    </requestFiltering>
  </security>
</system.webServer>
  1. 在客户端代码中,使用HttpClient或其他HTTP客户端库来向Web服务发送POST请求并附加文件。例如:
using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        var fileContent = new ByteArrayContent(<文件字节数组>);
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "<文件名>"
        };
        content.Add(fileContent);

        var response = await client.PostAsync("<Web服务URL>", content);
        response.EnsureSuccessStatusCode();
    }
}

请注意,上述代码中的一些部分可能需要根据您的需求进行调整

c# webservice传递文件给服务器处理

原文地址: http://www.cveoy.top/t/topic/iHu7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录