C# 在asp网络中传递大字符串并使用json获取答案
我正在尝试使用json在控制器中传递一个大字符串。我还需要控制器给我一个答案 这是我在web api中的控制器:C# 在asp网络中传递大字符串并使用json获取答案,c#,asp.net-mvc,asp.net-web-api,C#,Asp.net Mvc,Asp.net Web Api,我正在尝试使用json在控制器中传递一个大字符串。我还需要控制器给我一个答案 这是我在web api中的控制器: public class CustomersController : ApiController { // GET: api/Customers public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // G
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)
{
}
}
我需要我的web api读取我的字符串,然后向我发送答案,而不是将方法设置为
void
,您需要从控制器方法返回字符串值。
另外,别忘了用该方法负责服务的各自http谓词attribbte(HttpGet、HttpPost、HttpPut
等)来装饰这些方法
下面是一个示例,其中该方法返回一个Ok结果,这将生成一个http状态代码200,该代码的字符串位于响应体中
[HttpPost]
public IHttpActionResult Post([FromBody]string value)
{
return Ok(value);
}
然后是客户电话。
首先,您需要正确指定到控制器的路由
192.168.1.15:8282/api/Customers
然后,当使用应用程序/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();
}
}
一个好的开始是不要使控制器方法无效
。你找到一些例子或教程了吗?你的意思是在post方法中吗?是的。我不确定您使用的是什么版本的MVC/WebAPI,但我鼓励您这样做。网上有成千上万的例子。任何关于Web API的教程都会在第一课中介绍这一点。我在互联网上搜索了很多教程,但什么都找不到。也许我搜索错了。非常感谢,先生,但我的客户似乎没有发送任何东西…Post从我的http读取空值client@Dim看起来你的url是错误的,请尝试,更新了answerNow服务器它会回答我,但我null@Dim更新了答案
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();
}
}