none
How to use httpwebrequest post to fromform webapi? RRS feed

  • 问题

  • Hi, Guys,

    I had created a webapi, use post method, and , the parameter is using FromForm, like following:

    public JsonResult Save([FromForm]User user)

    It works fine via swagger to run the testing.

    However, when I used the winform program to run the testing, I used the httpwebrequest to post data to the webapi.

    In the webapi side, the user will always to an initial value, not the data from the httpwebrequest, does somebody have anyideas on it?

    The core program like following:

    string data = {  \"name\": \"John\"};

    System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
               
                byte[] bs = Encoding.UTF8.GetBytes(data);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.ContentLength = bs.Length;
                httpWebRequest.Method = "POST";
                httpWebRequest.Timeout = 20000;
                httpWebRequest.GetRequestStream().Write(bs, 0, bs.Length);
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
                string responseContent = streamReader.ReadToEnd();
                streamReader.Close();
                httpWebResponse.Close();
                httpWebRequest.Abort();
                return responseContent;

    Thanks.

    Jeffers

    2021年4月21日 8:07

全部回复

  • 你好,

    首先这里是中文论坛,请使用中文描述你的问题。

    其次如果你想询问有关asp.net的问题,你可以到下面的论坛进行提问。

    ASP.NET Forums

    此论坛仅讨论与.net framework相关的语言、技术以及IDE.

    如果以后有.net framework相关的问题,欢迎来这里提问。

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2021年4月22日 9:42
    版主