我是宁静服务的新手,我一直在创建一系列简单的控制台应用程序,以便更好地理解。我有一个simlple服务,我正在尝试发送数据,但我不断收到400错误的请求错误。我知道它必须是我忽略的简单事物。任何帮助将不胜感激。感谢
//service contract
[OperationContract, WebInvoke(Method = "POST", UriTemplate = "Test")]
bool Test(string input);
//service
public bool Test(string input)
{
Console.Out.WriteLine("recieved [" + input + "]");
return true;
}
//host program
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8889/TestImage");
WebServiceHost host = new WebServiceHost(typeof(ImageTestService), baseAddress);
try
{
host.Open();
Console.Out.WriteLine("TestService hosted at {0}", baseAddress.ToString());
Console.Out.WriteLine("hit enter to terminate");
Console.In.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
finally
{
if (host.State == CommunicationState.Faulted)
host.Abort();
else
host.Close();
}
}
}
//client program
// Create the web request
Uri address = new Uri("http://localhost:8889/TestImage/Test");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
StringBuilder data = new StringBuilder();
data.Append("input=" + HttpUtility.UrlEncode("12345"));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
postStream.Close();
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
}
答案 0 :(得分:0)
不确定这是您的问题的答案 - 但我有一个我一直用于表单发布的扩展方法:
public static HttpWebResponse DoFormPost(this HttpWebRequest request, string postVals, int timeoutSeconds)
{
request.Method = "POST";
request.Timeout = timeoutSeconds * 0x3e8;
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false;
byte[] bytes = Encoding.UTF8.GetBytes(postVals);
request.ContentLength = bytes.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
return (HttpWebResponse)request.GetResponse();
}
或者,既然您标记了WCF,那么还有另一个类似的问题:
Getting an http 400 error on calling a restful wcf service using http post
答案 1 :(得分:0)
不幸的是,我不确定你的代码有什么问题,乍一看似乎没问题。我想知道你使用的是UriTemplate。如果您的方法是“Test”且UriTemplate是“Test”,您可能需要使用此URL(两个“Test”字符串)调用它:
Uri address = new Uri("http://localhost:8889/TestImage/Test/Test");
我认为默认情况下方法名称是URL的一部分,因此在此之后应用模板。
对于HTTP错误,我使用名为Fiddler的工具进行故障排除。如果您可以创建一个与Request Builder一起使用的请求,那么只需要弄清楚如何通过您的代码生成该请求。
答案 2 :(得分:0)
您正在调用的WCF服务期望您传递的字符串以XML格式化!
以下对我有用:
string body = "foo";
string postData = @"<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'><![CDATA[" + body + "]]></string>";