6

I have a default mvc web api instance built from the Visual Studio 2012 template. It has the following routes and post method in the default ValuesController - the MVC site is unmodified from initial creation other than the contents of the Post method. Also, I'm using .NET framework 4.0 since I'm planning to target Azure.

Register method

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

and Post method

    // POST api/values
    public string Post([FromBody]string value)
    {
        if (value != null)
        {
            return "Post was successful";
        }
        else
            return "invalid post, value was null";
    }

I created a Console application which uses HttpClient to simulate posting to the service, but unfortunately the "value" coming in to the Post is always null. The Post method is successfully hit following the PostAsync call on HttpClient.

It's not clear to me how to map my request such that value contains the StringContent I'm passing in...

    static void Main(string[] args)
    {
        string appendUrl = string.Format("api/values");
        string totalUrl = "http://localhost:51744/api/values";
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("Accept", "application/xml");

        string content = "Here is my input string";
        StringContent sContent = new StringContent(content, Encoding.UTF8, "application/xml");

        HttpResponseMessage response = null;
        string resultString = null;

        client.PostAsync(new Uri(totalUrl), sContent).ContinueWith(responseMessage =>
            {
                response = responseMessage.Result;
            }).Wait();

        response.Content.ReadAsStringAsync().ContinueWith(stream =>
            {
                resultString = stream.Result;
            }).Wait();          
    }

I'm new to the MVC web api and use of HttpClient - any help pointing me in the right direction would be greatly appreciated.

1 Answer 1

6

Try the following code:

class Program {

    static void Main(string[] args) {

        HttpClient client = new HttpClient();
        var content = new StringContent("=Here is my input string");
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        client.PostAsync("http://localhost:2451/api/values", content)
            .ContinueWith(task => {

                var response = task.Result;
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            });

        Console.ReadLine();
    }
}

Have a look at the "Sending Simple Types" section of this blog post: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

Sign up to request clarification or add additional context in comments.

1 Comment

This was great! The two missing pieces from my original code were the equals sign (for simple types) and the ContentType. Adding those two pieces resolved the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.