使用ASP.NET WEB应用程序连接到REST API

时间:2019-01-16 14:31:55

标签: asp.net web-services

我的网站上有此代码,我正在尝试对此名为schooltime https://schooltimeapp.docs.apiary.io/#introduction/requirements-for-apps-using-the-schooltime-api的api进行POST请求。目前,我正在尝试将文本框中的4个值发布到REST api中,但是由于我是第一次使用C#连接到API,因此目前遇到了一些麻烦。

任何帮助将不胜感激,谢谢!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Web.Script.Serialization;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

    private const string URL = "https://school-time.co/app2/index.php/api/students/";
    private string urlParameters = "StRest@123";
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public class Result
    {
        public string id { get; set; }
        public string name { get; set; }
        public string email { get; set; }
        public string message { get; set; }
    }

    protected void Button_Add_Click(object sender, EventArgs e)
    {

        string name = TextBox_Name.Text;
        string pass = TextBox_Pass.Text;
        string email = TextBox_Email.Text;
        string birthdate = TextBox_Birth.Text;

        var webRequest = (HttpWebRequest)WebRequest.Create("https://school-time.co/app2/index.php/api/students/");

        var webResponse = (HttpWebResponse)webRequest.GetResponse(); if (webResponse.StatusCode == HttpStatusCode.OK)
        {



        }
        else Label1.Text = "Invalid Response";
    }

}

1 个答案:

答案 0 :(得分:0)

您可以使用RestSharp之类的客户端,然后使用Postman在C#中生成代码。

在您当前的设置下,Button_Add_Click中的类似内容可能会起作用(我尚未测试):

var webRequest = (HttpWebRequest)WebRequest.Create("https://school-time.co/app2/index.php/api/students/");

var postData = "name=hello";
    postData += "&email =world@test.com";
    //add other attributes...

var data = Encoding.ASCII.GetBytes(postData);

webRequest.Method = "POST";
webRequest.Headers.Add("ST-API-KEY", "StRest@123");
webRequest.ContentType = "application/json";

using (var stream = webRequest.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)webRequest.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

}