Как отправить переменные POST с помощью c #? - PullRequest
0 голосов
/ 21 июня 2011

У меня есть служба WCF REST, и я пытаюсь вручную поместить в нее некоторые данные, чтобы метод WCF получил их в качестве аргумента, но у меня возникли проблемы при определении, где в POST c # заполнить переменную.Метод WCF:

[OperationContract]
[WebInvoke]
string EchoWithPost(string message);

И до сих пор я удалил некоторый скрипт с сайта MSDN:

            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://localhost:52587/VLSContentService.svc/rest/EchoWithGet/Hello%20World");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            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();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

Я не совсем уверен, как перевести скрипт в некоторый код, который будетPOST 'сообщение' службе WCF.Кто-нибудь может помочь?

Ответы [ 2 ]

1 голос
/ 21 июня 2011

Конечные точки REST WCF по умолчанию понимают два типа данных: XML и JSON, поэтому оба способа, показанные ниже, должны работать нормально, поскольку операция ожидает string:

string postData = "\"This is a test that posts this string to a Web server.\"";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/json;

и

string postData = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">This is a test that posts this string to a Web server.</string>";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "text/xml;

Application-type application / x-www-form-urlencoded не поддерживается из WCF "из коробки" (но если вы получаете "jQuery support" из http://wcf.codeplex.com/, вы можете найтиповедение, которое поддерживает это).И если вы хотите получать какие-либо данные, в том числе неструктурированные (например, простой текст), вы можете найти дополнительную информацию по адресу http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx.

1 голос
/ 21 июня 2011

Я считаю, что правильные Postdata будут message=YOUR_ESCAPED_POSTDATA&additional=arguments, как выглядит запрос GET.

Вы можете, например, загрузить дополнение типа firebug и отправить обычную форму.Затем вы можете увидеть, как браузер отправляет свои пост-данные, и просто скопировать их.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...