1、向服务器发送数据可以利用webservice方法建立web服务接口,其他程序通过调用该接口发送数据。
(1)建立asmx页面前台:
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
(2)建立asmx接口后台,返回调用的json数据:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using System.Data;
/// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
/// <summary>
/// 服务也可提供参数,如果要求返还的是json类型,则返回aspnet包装过的json,即{d:content}形式
/// </summary>
/// <param name="enterpriseCode"></param>
/// <param name="region"></param>
/// <returns></returns>
[WebMethod]
public string HelloWorld(string enterpriseCode, string region)
{
return "hello world";
}
/// <summary>
/// 服务不需要传参数,参数存放到InputStream中,获取后解析,适用于不知道如何参数类型及参数个数的情况,直接传入整个字符串自行解析获取
/// </summary>
[WebMethod]
public void HelloWorld_InputStream()//类似于直接调用web页面
{
//调用方式可以是Content-Type: application/x-www-form-urlencoded(参数直接输入字符串或者json对象)或Content-Type: application/json(传入json字符串)
byte[] b = new byte[HttpContext.Current.Request.ContentLength];
//此处使用application/json时,流内部代码会将数据流读到最后,所以要重新定位
System.Web.HttpContext.Current.Request.InputStream.Position = 0;
HttpContext.Current.Request.InputStream.Read(b, 0, b.Length);
HttpContext.Current.Response.Write(System.Text.ASCIIEncoding.ASCII.GetString(b));
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.End();
}
/// <summary>
/// 服务需要参数,返回自定义json,不是返回{d:content}形式,而是自定义的书写形式
/// 此时可以使用Content-Type: application/x-www-form-urlencoded调用,参数字符串:enterpriseCode=123®ion=12332
/// 也可以通过Content-Type: application/json调用,参数字符串:{"enterpriseCode":"91330000573973053F","region":"330108"}
/// </summary>
/// <param name="enterpriseCode"></param>
/// <param name="region"></param>
[WebMethod]
public void HelloWorld_ContentType(string enterpriseCode, string region)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.Write("{ \"enterprissssqqqqeCode\":\"" + enterpriseCode + "\",\"region\":\"" + region + "\" }");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
/// <summary>
/// 获取全部验证码
/// </summary>
[WebMethod]
public void getCode()
{
string strCode = "";
try
{
DataTable dt = DataBase.getCode().Tables[0];
strCode = DataTableJson(dt);
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.StackTrace);
}
//HttpContext.Current.Response.Write("{\"access_code\":" + access_code + ",\"content\":" + access_content + "}");
HttpContext.Current.Response.Write("{\"content\":" + strCode + "}");
HttpContext.Current.Response.End();
}
public static string DataTableJson(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
if (dt.Rows.Count == 0)
{
jsonBuilder.Append("[]");
}
else
{
jsonBuilder.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < 2)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
else
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
} jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
}
return jsonBuilder.ToString();
}
}
2、ajax调用方式,如果contentType:"application/json",则data一定要json字符串:
(1)调用HelloWorld
$.ajax({
type: "POST",
url: "http://localhost:26012/WebService.asmx/HelloWorld",
data: "{\"enterpriseCode\":\"91330000573973053F\",\"region\":\"330108\"}",
contentType:"application/json",
//dataType: "json",
success: function (data) {
$('span').html(data.d);
},
error: function (errorContent,text,ex) {
$('span').html(errorContent);
}
});
(2)调用HelloWorld_InputStream,从Request.InputStream获取传入参数,可以传json或者json字符串,后台需要自己解析参数值
$.ajax({
type: "POST",
url: "http://localhost:26012/WebService.asmx/HelloWorld_InputStream",//可以直接传入json字符串或者json格式数据,Content-Type要设置"application/x-www-form-urlencoded"
data: "{\"enterpriseCode\":\"91330000573973053F\",\"region\":\"330108\"}",//以json字符串形式,jquery直接传入该字符串,建议使用,可以在后台转换成json格式
//data: { "enterpriseCode": "91330000573973053F", "region": "330108" },//以json形式,但是jquery会解析处理成"enterpriseCode=91330000573973053F®ion=330108"格式字符串
contentType: "application/x-www-form-urlencoded",//以form保存post数据,或者使用application/json
//dataType: "json",
success: function (data) {
$('span').html(data);
},
error: function (errorContent,text,ex) {
$('span').html(errorContent);
}
});
(3)调用HelloWorld_ContentType
通过Content-Type: application/json调用,建议使用该方式,参数json字符串:
"{\"enterpriseCode\":\"91330000573973053F\",\"region\":\"330108\"}"
$.ajax({
type: "POST",
url: "http://localhost:26012/WebService.asmx/HelloWorld_ContentType",//可以直接传入json字符串或者json格式数据
data: "{\"enterpriseCode\":\"91330000573973053F\",\"region\":\"330108\"}",//以json字符串形式
contentType: "application/json",
dataType: "json",
success: function (data) {
$('span').html(data);
},
error: function (errorContent,text,ex) {
$('span').html(errorContent);
}
});
结果:
通过Content-Type: application/x-www-form-urlencoded调用,参数字符串:enterpriseCode=123®ion=12332
或者json参数: { "enterpriseCode": "91330000573973053F", "region": "330108" },jquery会转换成上面形式
$.ajax({
type: "POST",
url: "http://localhost:26012/WebService.asmx/HelloWorld_ContentType",//可以直接传入json字符串或者json格式数据
data: "enterpriseCode=91330000573973053F®ion=330108",//以&分割的字符串
//data: { "enterpriseCode": "91330000573973053F", "region": "330108" },//以json形式,但是jquery会解析处理成"enterpriseCode=91330000573973053F®ion=330108"格式字符串
contentType: "application/x-www-form-urlencoded",//以form保存post数据
dataType: "json",
success: function (data) {
$('span').html(data);
},
error: function (errorContent,text,ex) {
$('span').html(errorContent);
}
});
或者
$.ajax({
type: "POST",
url: "http://localhost:26012/WebService.asmx/HelloWorld_ContentType",//可以直接传入json字符串或者json格式数据
//data: "enterpriseCode=91330000573973053F®ion=330108",//以&连接的字符串,不能传json字符串
data: { "enterpriseCode": "91330000573973053F", "region": "330108" },//以json形式,但是jquery会解析处理成"enterpriseCode=91330000573973053F®ion=330108"格式字符串
contentType: "application/x-www-form-urlencoded",//以form保存post数据
dataType: "json",
success: function (data) {
$('span').html(data);
},
error: function (errorContent,text,ex) {
$('span').html(errorContent);
}
});
结果:
demo下载地址:webservice的简单demo示例地址
https://download.csdn.net/download/yzy85/10455719
2、同时,也可以利用web页面建立网页发送接口,其他程序同样可以调用,原理一致,下面简单说明:
(1)页面接口
前台:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="uploadConfigData.aspx.cs" Inherits="WebApplication1.uploadConfigData" %>
后台:主要逻辑:接受处理POST数据并返回成功还是失败的json数据
protected void Page_Load(object sender, EventArgs e)
{
if (Request.RequestType.ToUpper() == "POST")
{
string error = "";
string newJson = PostInput();
if (!string.IsNullOrEmpty(newJson))
{
try
{
JObject jsonObj = JObject.Parse(newJson);
string deviceID = jsonObj["deviceId"].ToString();
JArray configJson = (JArray)jsonObj["collectItemConfig"];
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Response.Write(" {\"RESPONSECODE\": \"TRUE\" ,\"RESPONSEMESSAGE\": \"RECEIVE SUCCESS\"}");
}
else
{
Response.Write(" {\"RESPONSECODE\": \"FALSE\" ,\"RESPONSEMESSAGE\": \"" + error + "\"}");
}
}
else
{
Response.Write(" {\"RESPONSECODE\": \"FALSE\" ,\"RESPONSEMESSAGE\": \"" + "不是POST方式提交" + "\"}");
}
}
private string PostInput()
{
try
{
System.IO.Stream s = Request.InputStream;
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
using (Stream reqStream = Request.InputStream)
{
StreamReader sr = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8);
System.IO.StreamReader xmlStreamReader = sr;
builder.Append(sr.ReadToEnd());
}
s.Flush();
s.Close();
s.Dispose();
return builder.ToString();
}
catch (Exception ex)
{ throw ex; }
}
(2)C#调用接口处理,因为服务器端可能启用https,所以该处添加了证书验证,如果没有启用,可以将该段注释掉,逻辑:利用webrequest设置各项参数,直接将json数据post到服务器,然后接受返回的处理消息查看是否处理成功。
public static void SendJson(string url, string strJson, ref string strRes)
{
try
{
byte[] bs = Encoding.UTF8.GetBytes(strJson);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
System.Net.ServicePointManager.Expect100Continue = false;
req.KeepAlive = true;
req.Method = "POST";
req.ContentType = "application/json; ";
req.Accept = "application/json";
req.ContentLength = bs.Length;
req.Timeout = outTime;
// req.SendChunked = true;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = req.GetResponse())
{ //在这里对接收到的页面内容进行处理
StreamReader sr = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8);
System.IO.StreamReader xmlStreamReader = sr;
strRes = sr.ReadToEnd();
}
}
catch (Exception ex)
{
strRes = ex.Message;
}
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{ // 总是接受
return true;
}