发布:2021/4/1 11:02:44作者:管理员 来源:本站 浏览次数:1096
客户端:
static void Main(string[] args)
{
string _url = "http://localhost:55084//api/datasrv/setsuccess";
paraObject p1 = new paraObject() { term = "20191", studentno = "001", courseno = "i04bj_01" };
paraObject p2 = new paraObject() { term = "20191", studentno = "001", courseno = "i04bj_02" };
List<paraObject> list = new List<paraObject>();
list.Add(p1);
list.Add(p2);
//string jsonParam = "[{term:\"20191\",studentno:\"001\",courseno:\"i04bj_01\"},{term:\"20191\",studentno:\"001\",courseno:\"i04bj_02\"}]";
string jsonParam = Newtonsoft.Json.JsonConvert.SerializeObject(list);
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
byte[] byteData = Encoding.UTF8.GetBytes(jsonParam);
int length = byteData.Length;
request.ContentLength = length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, length);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
Console.WriteLine (responseString.ToString());
}
public class paraObject
{
public string term { get; set; }
public string studentno { get; set; }
public string courseno { get; set; }
}
接口:
[HttpGet]
[HttpPost]
public HttpResponseMessage setsuccess()
{
var apiset = DataAll.Dal.Select.SelectCourseImpl.getXfzSet();
if (!apiset.ApiOpen)
{
var robj = new resultObject();
robj.message = "API接口已关闭";
return new HttpResponseMessage { Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(robj), System.Text.Encoding.UTF8, "application/json") };
}
try
{
string vip = System.Web.HttpContext.Current.Request.UserHostAddress;
if (apiset.IP != vip)
{
throw new Exception(string.Format("访问IP:{0} 不在允许范围之内", vip));
}
var sr = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
var stream = sr.ReadToEnd();
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<DataAll.Api.paraObject>>(stream);
DataAll.Api.setSuccess(list);
return new HttpResponseMessage { Content = new StringContent("ok", System.Text.Encoding.UTF8, "application/json") };
}
catch (Exception e)
{
Common.Log.LogHelper.Info("失败:" + e.Message);
return new HttpResponseMessage { Content = new StringContent("err:" + e.Message, System.Text.Encoding.UTF8, "application/json") };
}
}