我正在尝试使用POST方法将JSON从控制台应用程序发送到WebPage.aspx 它将重新定义JSON并将对数据做一些思考。 请求状态是正常的,但在服务器端,我得到空的Request.form(非null只计数= 0)。 但是服务器需要从中读取数据。我写的代码就是与另一个页面集成的原型,这就是我需要在Request.form中发送数据的原因。
你帮忙解决我的帖子吗?
public async static void KeepMeLogged()
{
string urlPart = "ReadJson";
string BaseUrl = "https://baseurl/external-api/"
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
ForRequest json = new ForRequest
{
Login = Login
};
try
{
string stringJson = await Task.Run(() => JsonConvert.SerializeObject(json));
var httpContent = new StringContent(stringJson, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
// Do the actual request and await the response
var httpResponse = await httpClient.PostAsync(BaseUrl + urlPart, httpContent);
// If the response contains content we want to read it!
if (httpResponse.Content != null)
{
Console.WriteLine("IsOk");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public class ForRequest
{
[JsonProperty("login")]
public string Login { get; set; }
}
//ServerSide, Request.Form.Count always 0
public partial class ReadJsonPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form != null)
{
foreach (string key in Request.Form)
{
//Request.Form.Count == 0
//do something
}
}
}
}
答案 0 :(得分:1)
您可以使用以下代码获取json数据:
Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
using (var sr = new System.IO.StreamReader(Request.InputStream))
{
string json = sr.ReadToEnd();
}
答案 1 :(得分:1)
我找到了解决方案,如何在Request.form中发送JSON
MyClass json = new MyClass
{
Login = Login
};
string stringLogin = await Task.Run(() => JsonConvert.SerializeObject(logIn));
string URI = BaseUrl + urlPart;
string myParameters = "json=" + stringLogin;
try
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
string HtmlResult = wc.UploadString(URI, "POST", myParameters);
result = JsonConvert.DeserializeObject<Result>(HtmlResult);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}