Невозможно вызвать методы веб-сервисов RESTful - PullRequest
0 голосов
/ 17 июня 2010

Я пытаюсь погрузиться в мир веб-сервисов RESTful и начал со следующего шаблона:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Test {
   // TODO: Implement the collection resource that will contain the SampleItem instances

   [WebGet(UriTemplate = ""), OperationContract]
   public List<SampleItem> GetCollection() {
     // TODO: Replace the current implementation to return a collection of SampleItem instances
     return new List<SampleItem>() {new SampleItem() {Id = 1, StringValue = "Hello"}};
   }

   [WebInvoke(UriTemplate = "", Method = "POST"), OperationContract]
   public SampleItem Create(SampleItem instance) {
     // TODO: Add the new instance of SampleItem to the collection
      throw new NotImplementedException();
   }

   [WebGet(UriTemplate = "{id}"), OperationContract]
   public SampleItem Get(string id) {
      // TODO: Return the instance of SampleItem with the given id
      throw new NotImplementedException();
   }

   [WebInvoke(UriTemplate = "{id}", Method = "PUT"), OperationContract]
   public SampleItem Update(string id, SampleItem instance) {
      return new SampleItem {
               Id = 99,
               StringValue = "Done"
             };
   }

   [WebInvoke(UriTemplate = "{id}", Method = "DELETE"), OperationContract]
   public void Delete(string id) {
      // TODO: Remove the instance of SampleItem with the given id from the collection
      throw new NotImplementedException();
   }
}

Я могу выполнить операцию GET, но не могу выполнить PUT, POST илиУДАЛИТЬ запросы.

Может кто-нибудь объяснить мне, как выполнять эти операции и как создавать правильные URL-адреса?

С уважением

Алессандро

Ответы [ 2 ]

0 голосов
/ 17 июня 2010

РЕДАКТИРОВАТЬ - Обновлено в ответ на ваш ответ:

URL-адрес "http://localhost/test/Test.svc/MethodName"
postData - это данные, которые вы хотите передать в качестве параметра.

В вашем случае этопохоже, что вы пытаетесь передать тип. Помните, что это публикуется в URL. Разбейте значения типа на параметры.

Пример: "http://localhost/test/Test.svc/Create?id=123456&stringValue=newSampleItem"

Нужно изменить Операционный контракт, чтобы он принимал int и строку вместо SampleItem.

    [WebInvoke(UriTemplate = "Create?id={x}&stringValue={y}", Method = "POST"), OperationContract]
    public SampleItem Create(int id, string stringValue)
    {
       // Create and return the Sample Item. 
    }

Дайте мне знать, как это происходит.

Патрик.

Привет Алекс, Это то, что я использую для публикации в службе Restful ...

// Create the request
WebRequest request; 
request = WebRequest.Create(url + postData); 
request.Method = "POST";  

byte[] byteArray = Encoding.UTF8.GetBytes(postData); 
request.ContentType = "application/x-www-form-urlencoded"; 
request.ContentLength = byteArray.Length;

// Get the request stream. 
Stream dataStream = request.GetRequestStream(); 

// Write the data to the request stream. 
dataStream.Write(byteArray, 0, byteArray.Length); 

// Close the Stream object. 
dataStream.Close();

// Process the response
Stream responseStream; 
responseStream = request.GetResponse().GetResponseStream();

StreamReader objReader = new StreamReader(responseStream); 

StringBuilder sb = new StringBuilder(); 
string sLine = ""; 
int i = 0; 

while (sLine != null) 
{
    i++;
    sLine = objReader.ReadLine();
    sb.Append(sLine);
}

responseStream.Close();


string responseXML = sb.ToString()

Удачи,

Патрик

0 голосов
/ 17 июня 2010

Насколько я знаю, в данный момент WebInvoke поддерживает только GET и POST.Вместо этого я использую POST для выполнения действий PUT и DELETE.

...