我正在尝试使用json在控制器中传递一个大字符串。另外,我还需要管制员向我发送答案。
这是我在网络API中的控制器:
public class CustomersController : ApiController
{
// GET: api/Customers
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Customers/5
public string Get(int id)
{
return "value";
}
// POST: api/Customers
public void Post([FromBody]string value)
{
}
// PUT: api/Customers/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/Customers/5
public void Delete(int id)
{
}
}
首先我应该在哪里读取字符串以及应该在哪里发送答案?
这是我的客户端,尝试发送字符串
using (var client = new HttpClient())
{
var response = await client.PostAsync("http://192.168.1.15:8282/",new StringContent("Mystring", Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
}
我需要Web API来读取我的字符串,然后向我发送答案
答案 0 :(得分:1)
您需要从控制器方法中void
字符串值,而不是将方法设为return
。
另外,别忘了用方法负责服务的相应http动词属性(HttpGet, HttpPost, HttpPut
等)修饰方法。
在此示例中,该方法返回确定结果,这将生成一个http状态代码200,其中响应字符串位于字符串中
[HttpPost]
public IHttpActionResult Post([FromBody]string value)
{
return Ok(value);
}
然后进行客户呼叫。 首先,您需要正确指定到控制器的路由
192.168.1.15:8282/api/Customers
然后,在使用application/json
的内容类型时发送单个字符串作为内容是不合适的,因为json总是从对象{}
或数组[]
开始进行解析。
因此,发送单个字符串的最简单方法是将内容类型更改为application/x-www-form-urlencoded
,并在字符串前面添加一个=
符号
using (var client = new HttpClient())
{
var response = await client.PostAsync("http://192.168.1.15:8282/api/Customers",new StringContent("=Mystring", Encoding.UTF8, "application/x-www-form-urlencoded"));
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
}
}