5

我试图实现一个 REST WCF 以探索 PUT 和 POST 动词之间的区别。我已经使用该服务在某个位置上传了一个文件。

服务实现如下:

[OperationContract]
[WebInvoke(UriTemplate = "/UploadFile", Method = "POST")]
void UploadFile(Stream fileContents);

public void UploadFile(Stream fileContents)
{
 byte[] buffer = new byte[32768];
 MemoryStream ms = new MemoryStream();
 int bytesRead, totalBytesRead = 0;
 do
 {
       bytesRead = fileContents.Read(buffer, 0, buffer.Length);
       totalBytesRead += bytesRead;

       ms.Write(buffer, 0, bytesRead);
  } while (bytesRead > 0);

  using (FileStream fs = File.OpenWrite(@"C:\temp\test.txt")) 
  { 
      ms.WriteTo(fs); 
   }

  ms.Close();

}

客户端代码如下:

HttpWebRequest request =     (HttpWebRequest)HttpWebRequest.Create("http://localhost:1922   /EMPRESTService.svc/UploadFile");
        request.Method = "POST";
        request.ContentType = "text/plain";

        byte[] fileToSend = File.ReadAllBytes(@"C:\TEMP\log.txt");  // txtFileName contains the name of the file to upload. 
        request.ContentLength = fileToSend.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            // Send the file as body request. 
            requestStream.Write(fileToSend, 0, fileToSend.Length);
            //requestStream.Close();
        }

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
        Console.ReadLine();

文件正在上传,响应状态码返回“200 OK”。在上传位置存在或不存在文件的情况下,状态代码相同。

我已将 REST 动词更改为 PUT,状态代码与上述相同。

谁能解释一下,在这种情况下我如何识别动词之间的差异?我无法模拟从客户端代码生成连续请求。如果这样做的行为会有所不同,有人可以帮助我修改 ordrr 中的客户端代码以连续发送连续请求吗?

4

1 回答 1

2

当您创建新资源(在您的情况下为文件)时使用 POST 动词,重复操作会在服务器上创建多个资源。如果多次上传同名文件会在服务器上创建多个文件,则此谓词将有意义。

PUT 动词用于更新现有资源或创建具有预定义 ID 的新资源。多个操作将重新创建或更新服务器上的相同资源。如果第二次、第三次上传同名文件会覆盖之前上传的文件,这个动词就有意义了。

于 2012-05-13T17:48:07.710 回答