【发布时间】:2018-06-25 15:29:21
【问题描述】:
我正在尝试将带有 POST 方法的 JSON 从控制台应用程序发送到 WebPage.aspx 这将对 JSON 进行重新调整,并对数据进行一些思考。 请求状态是好的,但在服务器端我得到空的 Request.form (不是 null 只是 count = 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
}
}
}
}
【问题讨论】:
-
当json在同一个域/url中时,将json发布到端点是正常的。但是从控制台应用程序发布到 Web 端点。我相信你可能有 CORS 问题。
-
可惜我需要适配api,因为会和外软集成,所以不是我的方案:(
标签: c# asp.net json post request.form