用到知識:
1.?fetch的get,post
2. .net服務(wù)端api的跨域問題
3.?本地.net的服務(wù)端調(diào)試問題
注意問題:
1. 調(diào)用service時(shí)this的作用域問題
2. .net實(shí)現(xiàn)api的跨域允許,?在web.config進(jìn)行如下配置:

3.?直接使用vs調(diào)試模式下,使用地址localhost或者127.0.0.1發(fā)現(xiàn)react native無法調(diào)用,顯示
Network request faild。
解決辦法:配置服務(wù)系統(tǒng)到 IIS,?綁定其IP地址,?需要調(diào)試時(shí),把VS附加到IIS進(jìn)程?w3wp.exe.



4. Asp.net服務(wù)端所有的api應(yīng)該有返回值,不然在response.json()會報(bào)錯(cuò),?要么服務(wù)端必須有返回值,要么前端換方式
具體實(shí)現(xiàn):
1.?新建配置文件js用來存放api主域名地址如:
export const apiStr = 'https://facebook.github.io/';
2.?新建代碼文件IndexPageService.js用來存放調(diào)用api的代碼
a. fetch調(diào)用json文件示例代碼:
export function getMovies(callBack) {
? ? fetch(apiStr + `react-native/movies.json`)
? ? ? ? .then((response) => response.json())
? ? ? ? .then((responseJson) => {
? ? ? ? ? ? callBack(responseJson);
? ? ? ? })
? ? ? ? .catch((error) => {
? ? ? ? ? ? console.error(error);
? ? ? ? });
}
調(diào)用示例:需要注意this作用域
var _self = this;
? ? ? ? getMovies((d) => {
? ? ? ? ? ? _self.setState({
? ? ? ? ? ? ? ? dataSource: d.movies
? ? ? ? ? ? });
? ? ? ? });
b. fetch調(diào)用api的get示例
//get example
export function getExample(callBack) {
? ? fetch("http://192.168.31.41:8080/API/CRMTest/GET", {
? ? ? ? method: "GET"
? ? }).then((response) => response.json())
? ? ? ? .then((responseJson) => {
? ? ? ? ? ? callBack(responseJson);
? ? ? ? })
? ? ? ? .catch((error) => {
? ? ? ? ? ? console.error(error);
? ? ? ? });
}
c. fetch調(diào)用api的post方式
//post example
export function postExample() {
? ? var testModel = {
? ? ? ? Id: 1,
? ? ? ? Name: 'name'
? ? };
? ? fetch("http://192.168.31.41:8080/API/CRMTest/SaveData", {
? ? ? ? method: "POST",
? ? ? ? headers: {
? ? ? ? ? ? "Accept": "application/json",
? ? ? ? ? ? 'Content-Type': 'application/json',
? ? ? ? },
? ? ? ? body: JSON.stringify(testModel)
? ? }).then((response) =>
? ? ? ? response.json()
? ? ).then((responseJson) => {
? ? ? ? alert(responseJson);
? ? })
? ? ? ? .catch((error) => {
? ? ? ? ? ? console.error(error);
? ? ? ? });
}
Asp.net建WebApi簡約示例項(xiàng)目步驟





