2

I'm trying to send JSON with POST method from console application to WebPage.aspx which will regonize JSON and will do somethink with data. Request status is OK, but on server side I'm getting empty Request.form (not null just count = 0). But server will need to read data from. Code which I wrote just is the prototype of integration with another page, thats why I need to send data in Request.form.

Cah you help to fix my post?

    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
            }
        }

    }
}
4

2 回答 2

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);
}
于 2018-06-25T07:29:21.807 回答
1

您可以使用以下代码获取 json 数据:

Request.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
using (var sr = new System.IO.StreamReader(Request.InputStream))
{
    string json = sr.ReadToEnd();
}
于 2018-06-14T12:32:27.130 回答