C# 将数据从字符串值发布到asp net核心web api控制器方法
我有一个Asp Net Core 2.1应用程序,其中有一个REST控制器,如下所示:C# 将数据从字符串值发布到asp net核心web api控制器方法,c#,asp.net-core,C#,Asp.net Core,我有一个Asp Net Core 2.1应用程序,其中有一个REST控制器,如下所示: [Produces("application/json")] [Route("api/Test")] public class TestController : Controller { // GET: api/Test [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1",
[Produces("application/json")]
[Route("api/Test")]
public class TestController : Controller
{
// GET: api/Test
[HttpGet]
public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }
// GET: api/Test/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id) { return "value"; }
// POST: api/Test
[HttpPost]
public void Post([FromBody]string value)
{
//.. testing code..
}
// PUT: api/Test/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value) {}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id) {}
}
我正在使用内容类型“application/json”:如果我尝试使用“application/x-www-form-urlencoded”错误,则“我得到”(415)不支持的媒体类型。所以当我执行PostWebApi时,我在POST:api/Test方法中收到一个空值参数
如何接收我发送的数据
提前感谢。您可以使用HTTPClient进行此操作。这会让你的过程更轻松
public static string PostWebApi(string postData)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64817/api/test");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value", postData)
});
var result = await client.PostAsync("/api/Membership/exists", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
}
publicstaticstringpostwebapi(stringpostdata)
{
使用(var client=new HttpClient())
{
client.BaseAddress=新Uri(“http://localhost:64817/api/test");
var content=newformurlencodedcontent(new[]
{
新的KeyValuePair(“值”,postData)
});
var result=wait client.PostAsync(“/api/Membership/exists”,content);
字符串resultContent=wait result.Content.ReadAsStringAsync();
Console.WriteLine(结果内容);
}
}
参考:-能否显示示例“postData”字符串?您可以创建一个简单的对象
postData
,其中包含一个stringValue
类型的属性,并将该对象作为json发送。更改Api以获取此类型的对象
public static string PostWebApi(string postData)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64817/api/test");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("value", postData)
});
var result = await client.PostAsync("/api/Membership/exists", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
}