控制台应用程序HttpClient发布到mvc web api

时间:2012-11-03 12:06:23

标签: asp.net-mvc asp.net-web-api dotnet-httpclient

我有一个从Visual Studio 2012模板构建的默认mvc web api实例。它在默认的ValuesController中有以下路由和post方法 - MVC站点在初始创建时不会修改,而不是Post方法的内容。此外,我正在使用.NET framework 4.0,因为我计划将Azure定位。

注册方法

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

和Post方法

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

我创建了一个Console应用程序,它使用HttpClient来模拟发布到服务,但不幸的是,进入Post的“值”始终为null。在HttpClient上的PostAsync调用之后成功命中了Post方法。

我不清楚如何映射我的请求,以便值包含我传入的StringContent ...

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

我是MVC web api的新手,并使用HttpClient - 任何帮助我指向正确方向的人都会非常感激。

1 个答案:

答案 0 :(得分:6)

请尝试以下代码:

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

查看此博文的“发送简单类型”部分:http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1