Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我得不到“访问控制允许来源”?_C#_Asp.net_.net_Api - Fatal编程技术网

C# 为什么我得不到“访问控制允许来源”?

C# 为什么我得不到“访问控制允许来源”?,c#,asp.net,.net,api,C#,Asp.net,.net,Api,我有用vue.js编写的前端和后端.net API。我尝试获取对象,但收到错误,我不知道发生了什么。 我的错误: Access to XMLHttpRequest at 'http://localhost:50598/weatherforecast' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on t

我有用vue.js编写的前端和后端.net API。我尝试获取对象,但收到错误,我不知道发生了什么。 我的错误:

Access to XMLHttpRequest at 'http://localhost:50598/weatherforecast' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我的代码在控制器中,这里我设置了一个断点

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : Controller
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}
}

和vue js脚本

<script>
import axios from 'axios'
const API_URL = 'http://localhost:50598/';
export default {
    name: "FetchData",
    data() {
        return {
            forecasts: []
        }
    },
    methods: {
        getWeatherForecasts() {
            axios.get(`${API_URL}weatherforecast`)
                .then((response) => {
                    this.forecasts =  response.data;
                })
                .catch(function (error) {
                    alert(error);
                });
        }
    },
    mounted() {
        this.getWeatherForecasts();
    }
}
如果我必须显示更多代码,则写下

信息很清楚:

请求的资源上不存在“Access Control Allow Origin”标头

因此,您正在执行跨来源请求;i、 e:表格https://example1.com:someotherport 到https://example2.com:someport,并且由于缺少标题,浏览器会阻止它

如果出现以下情况,则会发生错误:

CORS未配置 已配置CORS,但由于内部服务器错误或类似原因,未附加标头。
请查看此MSDN文档以解决此问题:

问题很清楚:请求的资源上不存在“Access Control Allow Origin”标题确定但我应该在何处添加Access Control Allow Origin假设您正在使用.net 5:否则,您可以在web上搜索COR和您正在使用的框架