无法使用c#asp.net连接到REST api

时间:2019-01-17 06:07:23

标签: c# asp.net json web-services

我在我的网站上有此代码,它只是一个按钮,我正尝试向名为上学时间https://schooltimeapp.docs.apiary.io/#introduction/requirements-for-apps-using-the-schooltime-api的这个API发出POST请求。目前,我正在尝试将2个值发布到REST api中,但是由于var = response不断给我这个错误System.Net.WebException: 'The remote server returned an error: (403) Forbidden.,我遇到了一些麻烦,谢谢您的帮助!

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;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Btn_Add_Click(object sender, EventArgs e)
    {
        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();

    }
}

0 个答案:

没有答案