C# 错误:-在调用begin getresponse之前,必须将contentlength字节写入请求流
我正在尝试使用.NETCore创建RESTWebAPI 我有不同的WebMethods,但仍停留在[HttpPost]功能中,如下所示:C# 错误:-在调用begin getresponse之前,必须将contentlength字节写入请求流,c#,json,asp.net-core,asp.net-core-webapi,C#,Json,Asp.net Core,Asp.net Core Webapi,我正在尝试使用.NETCore创建RESTWebAPI 我有不同的WebMethods,但仍停留在[HttpPost]功能中,如下所示: [HttpPost] public string Post([FromBody] string s) { s = “new”; return s; } 并尝试使用Windows窗体中的按钮从我的客户端调用,如下所示: private void button_Click(object sender, EventArgs e) {
[HttpPost]
public string Post([FromBody] string s)
{
s = “new”;
return s;
}
并尝试使用Windows窗体中的按钮从我的客户端调用,如下所示:
private void button_Click(object sender, EventArgs e)
{
string requestMethod =string.Formate(“api/Service”);
string result;
string s=”old”;
//There is a class Rest_Client with constructor to assign values of localhost url, Method type(GET/PUT/Post), Content-type and PostData)
Rest_Client client =new Rest_Client(localhost, PostRequest, s);
result = client.MakeRequest(requestMethod);
MessageBox.Show(result);
}
Rest_客户端类中的函数:-
public string MakeRequest(string parameters)
{
var request =(HttpWebREquest)WebRequest.Create(localhost+parameters);
request.Method=Post;
request.ContentLength =1;
request.ContentType=”application/json”;
//there are different function too for Get/PUT. for now i need only Post .
if(!string.IsNullorEmpty(PostData)&&Method==HttpVerb.POST)
{
var bytes=Encoding.UTF8.GetBytes(PostData);
reuest.ContentLength=bytes.Length;
StreamWriter streamWriter =new StreameWriter(REquest.GetREquestStream());
streamWriter.Write(bytes);
}
var response =(HttpWebResponse)request.GetResponse());
var responseValue=string.Empty;
var responseStream=response.GetResponseStream())
if(responseStream!=N=null)
{
using(var reader =new StreamREader(responseStream))
{
ReponseValue=readerReadToEnd();
}
}
return responseValue;
}
但是我得到一个错误,您必须在调用begin getresponse之前将contentlength字节写入请求流
我是C#新手,不知道代码出了什么问题 在HTTP中,内容长度报头位于数据之前,因此是的:在开始写入之前,您需要告诉它将有多少数据(除非您使用分块编码)——否则它需要缓冲内存中的所有数据,这是次优的;数据从哪里来?你能知道长度吗?正如我在文章中提到的:在我的服务器端有一个名为post的公开函数返回字符串,当我从客户端调用它时,我在PostData参数中传递参数值。在HTTP中,内容长度头位于数据之前,所以是的:在开始编写之前,您需要告诉它将有多少数据(除非您使用分块编码)——否则它需要缓冲内存中的所有数据,这是次优的;数据从哪里来?你能知道长度吗?正如我在文章中提到的:在我的服务器端有一个名为post的公开函数返回字符串,当我从客户端调用它时,我在PostData参数中传递参数值。