Ajax跨域调用WebApi接口方法,后台json格式传参数

界面调用webapi接口按钮控件:

  <asp:button runat="server" ID="btn" Text="跨域调用接口测试" CssClass="BtnList" OnClick="btn_Click" />

按钮事件:

  protected void btn_Click(object sender, EventArgs e)
        {
            //json格式模型
            Model Mp = new Model();
            Mp.Header = "MG_License";
            Mp.Flag = "Update";

            List listBody = new List();
            Body bodyOne = new Body();
            bodyOne.LicenseCode = "91758dfc-ab2a-48a9-a699-9512d68c921c";
            bodyOne.ACcountsID = "016b3f9044de413189a96203ed324abd";
            bodyOne.MacAddress = "88-E5-65-E1-01-25";

            listBody.Add(bodyOne);

            Mp.Body=listBody;
            string [] AdditionalContent=new  string[0];          
            Mp.Additional = AdditionalContent;

            //将模型转换成json格式字符串
            string _json = JsonConvert.SerializeObject(Mp);
            _json = "[" + _json + "]";
            this.WriteAjaxMessage("UseWebApi('" + _json + "');");//因为接口参数的类型为字符串,所以加上''
        } 
#region 模型类
    public class Model
    {
        public string Header { get; set; }
        public string Flag { get; set; }

        public List Body { get; set; }
        public string[] Additional { get; set; }       
    }
    public class Body
    {
        public string LicenseCode { get; set; }
        public string ACcountsID { get; set; }
        public string MacAddress { get; set; }
    }  
#endregion

前台脚本方法:UseWebApi()

 

代理服务(该处是GET服务),即建一般处理程序__agent.ashx

public void ProcessRequest(HttpContext context)
        {
            string __oraclerequestaddress = HttpUtility.UrlDecode(context.Request.QueryString["url"]);
            System.Net.HttpWebRequest __agentrequest = System.Net.WebRequest.Create(__oraclerequestaddress) as System.Net.HttpWebRequest;
            string __remoteresponsetext = string.Empty;
            using (System.IO.StreamReader __responsereader = new System.IO.StreamReader(__agentrequest.GetResponse().GetResponseStream()))
                __remoteresponsetext = __responsereader.ReadToEnd();
            context.Response.Write(__remoteresponsetext);
        }

注:需引用jquery.min.js。。。

你可能感兴趣的:(JSON,AJAX,WebApi,ajax,json,webapi)