Writing a REST service to upload a file in C#

空扰寡人 提交于 2019-12-14 04:02:08

问题


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:

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

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

Code - IFileUploaderService

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

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

<?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.


回答1:


Add:

requestStream.Close();

before this line:

string result;

This will cause the stream to flush.



来源:https://stackoverflow.com/questions/47135772/writing-a-rest-service-to-upload-a-file-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!