asp.net web api-如何将普通C#winForms应用程序中的字符串发布到WepApi函数
本文关键字:字符串 函数 WepApi 应用程序 C#winForms api- web net asp | 更新日期: 2023-09-27 17:59:27
我已经搜索了一个好的例子或解释,但找不到任何有用的东西。
我有一个ApiController TestController
,那里有一个后功能
public void Post([FromBody] string value)
{
//something
}
我该怎么做才能从WinForms应用程序向该函数发送一个类似"test"的简单字符串?注意:我的问题是不要使用在许多不同方面都能正常工作的函数。问题是该值始终为null。
我使用以下方法,对我来说效果很好。
// Create a WebRequest to the remote site
WebRequest myWebClient = WebRequest.Create(uri);
myWebClient.ContentType = "application/xml";
myWebClient.Method = method;
// Apply ASCII Encoding to obtain the string as a byte array.
string postData = //Data you want to post;
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(postData);
Stream dataStream = myWebClient.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// Call the remote site, and parse the data in a response object
System.Net.WebResponse response = myWebClient.GetResponse();
// Check if the response is OK (status code 200)
//if (response.StatusCode == System.Net.HttpStatusCode.OK)
//{
// Parse the contents from the response to a stream object
System.IO.Stream stream = response.GetResponseStream();
// Create a reader for the stream object
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
// Read from the stream object using the reader, put the contents in a string
string contents = reader.ReadToEnd();
如果您想发布对象,这将把对象序列化为xml。
public string ToXml(object Obj, System.Type ObjType)
{
XmlSerializer ser = default(XmlSerializer);
ser = new XmlSerializer(ObjType);
MemoryStream memStream = default(MemoryStream);
memStream = new MemoryStream();
XmlTextWriter xmlWriter = default(XmlTextWriter);
xmlWriter = new XmlTextWriter(memStream, Encoding.UTF8);
xmlWriter.Namespaces = true;
ser.Serialize(xmlWriter, Obj);
xmlWriter.Close();
memStream.Close();
string xml = null;
xml = Encoding.UTF8.GetString(memStream.GetBuffer());
xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
return xml;
}
尝试从System.Net.Http.dll
:使用HttpClient
using (var loClient = new HttpClient() { BaseAddress = new Uri("http://localhost:55743/") })
{
var loResult = loClient.PostAsJsonAsync<string>("api/Test/Post/", "Hello World");
loResult.Result.EnsureSuccessStatusCode();
}
使用WebClient
:可以很容易地完成大多数基本任务
using (var wc = new WebClient())
{
wc.Headers.Add("Content-Type", "application/json");
var response = wc.UploadString("http://provide-url", "'"test'"");
}
EDIT:原来您需要将客户端中的Content-Type
指定为application/json
AND将字符串用额外的引号括起来。
根据这篇文章,它与Web API处理参数绑定的方式有关。