gpt4 book ai didi

asp.net-mvc - 控制台应用程序 HttpClient 发布到 mvc web api

转载 作者:行者123 更新时间:2023-12-04 15:01:34 25 4
gpt4 key购买 nike

我有一个从 Visual Studio 2012 模板构建的默认 mvc web api 实例。它在默认的 ValuesController 中有以下路由和 post 方法 - 除了 Post 方法的内容之外,MVC 站点在初始创建时没有被修改。此外,我正在使用 .NET 框架 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";
}

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

我不清楚如何映射我的请求,以便值包含我传入的 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 的新手 - 任何为我指明正确方向的帮助将不胜感激。

最佳答案

试试下面的代码:

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

关于asp.net-mvc - 控制台应用程序 HttpClient 发布到 mvc web api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13209010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com