开发者

Help with simple restful post problem

I am new to restful services and I have been creating a series of simple console apps to better understand. I have a simlpl开发者_运维百科e service that I am trying to send data to but I keep getting a 400 bad request error. I know it has to be something simple I overlooked. Any help would be greatly appreciated. Thanks

//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());
}


Not sure that is answers your question - but I have an extension method I have been using for form post:

    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();
    }

Or since you tagged WCF, then there is also another similar question:

Getting an http 400 error on calling a restful wcf service using http post


Unfortunately, I'm not sure what's wrong with your code, it looks okay at first glance. I wonder if it's the UriTemplate that you're using. If your method is "Test" and the UriTemplate is "Test", you might need to call it with this URL (two "Test" strings):

Uri address = new Uri("http://localhost:8889/TestImage/Test/Test");

I believe the method name is part of the URL by default, so the template gets applied after that.

With HTTP errors, I use a tool called Fiddler to troubleshoot. If you can create a request that works with the Request Builder, it's just a matter of figuring out how to produce that request via your code.


The WCF service you are calling is expecting the string you are passing to be serialized in XML!

The following has worked for me in the past:

string body = "foo";
string postData = @"<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/'><![CDATA[" + body + "]]></string>";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜