Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console app HttpClient post to mvc web api

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.

like image 730
jtoth3 Avatar asked Nov 03 '12 12:11

jtoth3


Video Answer


1 Answers

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

like image 102
tugberk Avatar answered Nov 03 '22 01:11

tugberk