1. 程式人生 > 實用技巧 >.net+uniapp 前後端資料互動相關問題記錄

.net+uniapp 前後端資料互動相關問題記錄

uniapp 提交form表單

@submit EventHandle 攜帶 form 中的資料觸發 submit 事件,event.detail = {value : {'name': 'value'} , formId: ''},report-submit 為 true 時才會返回 formId
@reset EventHandle 表單重置時會觸發 reset 事件
<form @submit="formSubmit" @reset="formReset">
    <view class="uni-btn-v">
        <button form-type="submit">Submit</button>
        <button type="default" form-type="reset">Reset</button>
    </view>
</form>
methods: {
    formSubmit: function(e) {
        console.log('form發生了submit事件,攜帶資料為:' + JSON.stringify(e.detail.value))
        var formdata = e.detail.value
        uni.showModal({
        content: '表單資料內容:' + JSON.stringify(formdata),
        showCancel: false
        });
    },
    formReset: function(e) {
        console.log('清空資料')
    }
}

網路請求 uni.request

import $config from "@/appConfig.js"; //呼叫url字首 *注意修改為自己的!!!
url: $config.SERVER_URL + 'api/sys/user/modify/uploadPic', //自行修改各自的對應的介面 

參考連結

.net接受前端form表單的資料

//form 的提交方式是Get
request.QueryString[key]
//form 的提交方式是Post
string result = null;
using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, Encoding.UTF8, true, 2048, true))
{
    string inputStream = sr.ReadToEnd();
    JObject jsonObj = JObject.Parse(inputStream);
    if (jsonObj != null)
    {
    	result = Convert.ToString(jsonObj[key]);
    }
}
public static  string GetRequestString(string key, HttpRequestBase request)
        {
            string result = null;
            if (request.Form.Get(key) != null && request.Form.Get(key).ToString() != "")
            {
                result = request.Form.Get(key).ToString();
            }
            else if (request.QueryString[key] != null && request.QueryString[key].ToString() != "")
            {
                result = request.QueryString[key].ToString();
            }
            else if (request.HttpMethod.ToUpper() == "POST")
            {
                try
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, Encoding.UTF8, true, 2048, true))
                    {
                        string inputStream = sr.ReadToEnd();
                        JObject jsonObj = JObject.Parse(inputStream);
                        if (jsonObj != null)
                        {
                            result = Convert.ToString(jsonObj[key]);
                        }

                        request.InputStream.Position = 0;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.LogError("從Post引數中獲取資料出現異常", ex);
                    return null;
                }

            }
            return result;
        }
		

.net向前端響應Json資料

可參考連結:https://www.cnblogs.com/litian/p/3870975.html

  • 建立一個結果響應的Model
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace demo3.Models
{
    public class ResultModel
    {
        public string name
        {
            get; set;
        }
    }
}
  • 設定響應的結果值,進行json序列化
public string getForm()
{
    //設定響應結果
    ResultModel res = new ResultModel();
    res.name = "test";
	//使用JSonConvert序列化
    string rsp = JsonConvert.SerializeObject(res);
    return rsp;
}

response 響應xml資料

string reMessage = "<?xml version='1.0'?><xml>"
                    + "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName >"
                    + "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName >"
                    + "<CreateTime>" + CreateTime + "</CreateTime>"
                    + "<MsgType><![CDATA[text]]></MsgType >"
                    + "<Content><![CDATA[未找到相關內容]]></Content >"
                    + "</xml>";
 //建立XmlDocument物件,將符合xml格式的字串載入到dom中
 XmlDocument xdoc = new XmlDocument();
//string轉xml
 xdoc.LoadXml(reMessage);
 Response.Write(xdoc.DocumentElement.OuterXml);

獲取xml

//獲取流
Stream requestStream = Request.InputStream;
byte[] requestByte = new byte[requestStream.Length];
requestStream.Read(requestByte, 0, (int)requestStream.Length);

//獲取xml包
string temStr = Encoding.UTF8.GetString(requestByte);

//將xml文件載入到DOM中
XmlDocument doc = new XmlDocument();
doc.LoadXml(temStr);

//獲取根節點
Debug.WriteLine(doc.DocumentElement.OuterXml);

//獲取子節點
XmlNode xmlNode = doc.FirstChild;
if (xmlNode.HasChildNodes)
{
    for (int i = 0; i < xmlNode.ChildNodes.Count; i++)
    {
    	Debug.WriteLine(xmlNode.ChildNodes[i].InnerText);
    }
}

//獲取最後一個子節點
Debug.WriteLine(xmlNode.LastChild.OuterXml);

//查詢節點 xpath方式 或者 GetElementByID檢索節點
XmlNode node = doc.DocumentElement.SelectSingleNode("FromUserName");
Debug.WriteLine(node.InnerText);
string openId = node.InnerText;

//獲取ToUserName
string ToUserName = doc.DocumentElement.SelectSingleNode("ToUserName").InnerText;
string FromUserName = doc.DocumentElement.SelectSingleNode("FromUserName").InnerText;
string CreateTime = doc.DocumentElement.SelectSingleNode("CreateTime").InnerText;
string MsgType = doc.DocumentElement.SelectSingleNode("MsgType").InnerText;
string Content = doc.DocumentElement.SelectSingleNode("Content").InnerText;
string MsgId = doc.DocumentElement.SelectSingleNode("MsgId").InnerText;

發起get請求

//傳送http get請求
string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
//建立請求
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.ContentType = "application/json;encoding=utf-8";

//獲取響應  
WebResponse response = req.GetResponse();//未響應
Stream stream = response.GetResponseStream();
//解碼資料流
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8"));
string temString = reader.ReadToEnd();
var jObject = JObject.Parse(temString);
var access_token = jObject["access_token"].ToString();//獲取time{"time":"2016-06-06 11:11:11"}

//JavaScriptSerializer s = new JavaScriptSerializer();
//Dictionary<string, string> dict = (Dictionary<string, string>)s.DeserializeObject(temString);
//string access_token = dict["access_token"];

Console.WriteLine(temString);
//關閉io流
reader.Close();
stream.Close();

發起post請求

//建立請求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json;encoding=utf-8";
//request.ContentLength = Encoding.UTF8.GetByteCount(postData);


//#region 新增Post 引數(menu需要post的引數)
byte[] data = Encoding.UTF8.GetBytes(menu);
request.ContentLength = data.Length;
using (Stream reqStream = request.GetRequestStream())
{
    reqStream.Write(data, 0, data.Length);
    reqStream.Close();
}
//獲取響應
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
//解碼
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
//響應結果
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
ViewBag.MyMessage = retString;

讀取txt檔案

//獲取選單內容
FileStream fs1 = new FileStream(Server.MapPath("~/") + "\\App_Data\\menu.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs1, Encoding.GetEncoding("GBK"));
string menu = sr.ReadToEnd();
sr.Close();
fs1.Close();

字串轉json

string temString = getUserInfo_Access_token(code);
//轉化為json字串
var json = JObject.Parse(temString);
//獲取access_token欄位
string access_token = json["access_token"].ToString();