使用WCF REST在PUT和POST之间的区别

tec*_*mad 5 c# wcf wcf-rest

我试图实现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();
Run Code Online (Sandbox Code Playgroud)

}

客户端代码如下:

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();
Run Code Online (Sandbox Code Playgroud)

正在上载文件,响应状态代码将返回"200 OK".在上传位置存在或不存在文件的情况下,satus代码是相同的.

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

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

Dmi*_* S. 2

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

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