【发布时间】:2022-01-26 03:07:48
【问题描述】:
到目前为止我做了什么:
我已将我的网站 .net framework 4.7.1 添加到 IIS 中,我浏览了该网站并在 http://localhost 上工作,我将所有 Web 文件添加到 wwwroot。
我有一个扩展 Api 控制器的值控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace NewsFeedWebApi.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody] string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
这是我的 React Native 代码:
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React, { useState, useEffect } from 'react';
import { Button, View, Text, StyleSheet, TouchableOpacity, } from 'react-native';
function App() {
useEffect(() => {
// Update the document title using the browser API
function GetInit(){
fetch('https://192.168.1.32:80/api/values')
.then((response) => response)
.then((json) => {
console.log(json);
})
.catch((error) => {
//alert(error);
console.log(error);
});
}
GetInit();
});
return (
<View><Text>wwww</Text></View>
);
}
export default App;
在 webconfig 中我添加了这个来启用 cors:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
有人可以告诉我我在哪里犯了错误或缺少什么吗?
【问题讨论】:
-
“我浏览了网站”,你是说你使用了 MVC 并且你访问了一个特殊的页面,还是你的意思是你对每个请求都有一个简单的响应?如果是后者,那么您需要确保必须从 react native 发送最少的标头集。为了测试我会在 Postman 或类似的东西上测试它。
-
您想检查您的 react native 应用程序发送的标头。许多方法包括调试(可能需要在 ASP Web api 中为您正在测试的任何内容注入一些参数)或 Fiddler。
-
啊,使用 https 而不是 http。
标签: c# react-native asp.net-web-api