0

I'm trying to post a request from one server to a second, which is using the WebAPI techology. This is my method that receives the call

[HttpGet]
    [HttpPost]
    public HttpResponseMessage MyMethod([FromBody] string token, [FromBody] string email, [FromBody] string password)
    {

        string a = "hello world!";
        return new HttpResponseMessage() { Content = new StringContent(a) };
    }

I am using this code post to to it:

using (var c = new WebClient())
        {
            //string obj = ":" + JsonConvert.SerializeObject(new { token= "token", email="email", password="password" });
            NameValueCollection myNameValueCollection = new NameValueCollection();

            // Add necessary parameter/value pairs to the name/value container.
            myNameValueCollection.Add("token", "token");
            myNameValueCollection.Add("email", "email");

            myNameValueCollection.Add("password", "password");

            byte[] responseArray = c.UploadValues("MyServer/MyMethod", "POST", myNameValueCollection);


            return Encoding.ASCII.GetString(responseArray);
        }

I've tried several alternatives.

This one I wrote above gives me an Internal Server Error and My breakpoint inside MyMethod isn't hit, so the problem is not on my method's code.

Commenting the three lines that add parameters to my nameValueCollection, I get a 404.

Removing the parameters form the signature of MyMethod, it works.

I would like to post this information to my server that hosts the API.

Do you know what I am doing wrong?

4

1 回答 1

1

As always start by writing a view model:

public class MyViewModel 
{
    public string Token { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

that your controller action will take as parameter:

[HttpPost]
public HttpResponseMessage MyMethod(MyViewModel model)
{

    string a = "hello world!";
    return new HttpResponseMessage() { Content = new StringContent(a) };
}

Notice that I have gotten rid of the [HttpGet] attribute. You gotta choose the verb. And by the way if you follow the standard ASP.NET Web API routing convention, the name of your action should correspond to the HTTP verb that is being used to access it it. It's standard RESTful convention.

Now you can hit it:

using (var c = new WebClient())
{
    var myNameValueCollection = new NameValueCollection();

        // Add necessary parameter/value pairs to the name/value container.
    myNameValueCollection.Add("token", "token");
    myNameValueCollection.Add("email", "email");
    myNameValueCollection.Add("password", "password");

    byte[] responseArray = c.UploadValues("MyServer/MyMethod", "POST", myNameValueCollection);

    return Encoding.ASCII.GetString(responseArray);
}
于 2013-09-29T18:53:59.947 回答