编写REST服务以使用C#上传文件 [英] Writing a REST service to upload a file in C#

查看:136
本文介绍了编写REST服务以使用C#上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个REST服务来上传文件.似乎有问题.每当我尝试使用测试控制台应用程序上传文件时,都会出现以下错误:

I have written a REST service to upload a file. Seems like there is an issue. Whenever i try to upload the file using a test console application it gives me an error mentioned below:

类型为'System.Net.WebException'的未处理异常发生在 System.dll

An unhandled exception of type 'System.Net.WebException' occurred in System.dll

其他信息:远程服务器返回错误:(400)错误 请求.

Additional information: The remote server returned an error: (400) Bad Request.

代码-IFileUploaderService

Code - IFileUploaderService

[OperationContract]
    [WebInvoke(Method = "POST",
        UriTemplate = "/UploadImage", 
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json)]
    void FileUpload(Stream stream);  

代码-FileUploaderService.svc.cs

Code - FileUploaderService.svc.cs

public void FileUpload(Stream stream)
    {
        string FilePath = Path.Combine(HostingEnvironment.MapPath("~/FileServer/Uploads"), "1.txt");

        int length = 0;
        using (FileStream writer = new FileStream(FilePath, FileMode.Create))
        {
            int readCount;
            var buffer = new byte[8192];
            while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                writer.Write(buffer, 0, readCount);
                length += readCount;
            }
        }
    }

Web.Config

Web.Config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1"/>
  </system.web>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="UploaderService.FileUploaderService" maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647"
                 transferMode="Streamed"
                 sendTimeout="00:05:00">
          <readerQuotas  maxDepth="2147483647"
                         maxStringContentLength="2147483647"
                         maxArrayLength="2147483647"
                         maxBytesPerRead="2147483647"
                         maxNameTableCharCount="2147483647"/>
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows"></transport>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="UploaderService.FileUploaderService" behaviorConfiguration="UploaderService.FileUploaderService">
        <endpoint address="" binding="webHttpBinding" contract="UploaderService.IFileUploaderService" behaviorConfiguration="web">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="UploaderService.FileUploaderService">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

控制台应用程序上传文件:

Console Application to upload the file:

static void Main(string[] args)
    {

        System.Uri url = new System.Uri("http://localhost:8082/FileUploaderService.svc/uploadimage");
        string filePath = @"C:\test.jpg";



        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Accept = "application/octet-stream";
        request.Method = "POST";
        request.ContentType = "image/jpeg";
        using (Stream fileStream = File.OpenRead(filePath))
        using (Stream requestStream = request.GetRequestStream())
        {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int byteCount = 0;
            while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
            {
                requestStream.Write(buffer, 0, byteCount);
            }
        }
        string result;
        using (WebResponse response = request.GetResponse())
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            result = reader.ReadToEnd();
        }
        Console.WriteLine(result);
    }

我在其他地方也看到了提到的解决方案,但是它没有用.有人可以帮助我吗,因为我想知道自己在做错什么.

I have seen the solutions mentioned in other places but it's not working. Can someone help me on this since i am wondering what am i doing wrong.

推荐答案

添加:

requestStream.Close();

在此行之前:

string result;

这将导致流冲洗.

这篇关于编写REST服务以使用C#上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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