Javascript 阿贾克斯赢了';t从web api c返回值#

Javascript 阿贾克斯赢了';t从web api c返回值#,javascript,c#,asp.net-web-api,Javascript,C#,Asp.net Web Api,我用C#创建了一个简单的web api,它是一个返回字符串的方法 public string Get() { return "Welcome Web API online"; } 我现在通过javascript调用它,它成功地命中了doe,但是它不会返回任何数据,它总是落在错误函数中 var url = "https://localhost:44381/api/accounts"; $.ajax({ type: 'GET', dataT

我用C#创建了一个简单的web api,它是一个返回字符串的方法

    public string Get()
    {
        return "Welcome Web API online";
    }
我现在通过javascript调用它,它成功地命中了doe,但是它不会返回任何数据,它总是落在错误函数中

var url = "https://localhost:44381/api/accounts";

$.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    success: function (data) {
        console.log(data);
    },
    error: function (data) { console.log(data); }
});
检查控制台日志,它显示:

跨源请求被阻止:同一源策略不允许读取远程资源


请告诉我。

当我们使用Ajax、angular等访问具有不同来源的URL时,需要在不同的来源端处理CORS(跨来源请求共享)。 在您的web api项目中使用下面的代码。在Global.asax.cs文件中

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

我的请求可能会对您有所帮助。它对我很有用。

当我们使用Ajax、angular等访问具有不同来源的URL时,需要在不同来源端处理CORS(跨来源请求共享)。 在您的web api项目中使用下面的代码。在Global.asax.cs文件中

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

我的系统可能会对您有所帮助。它对我很有用。

您需要启用CORS并设置一个允许的主机列表,这将允许您的后端接收来自不同主机的请求。也许这有帮助:@Sahil great help谢谢:)@Rumpelstinsk收到了。。现在我知道你需要启用CORS并设置一个允许的主机列表,这将允许你的后端接收来自不同主机的请求。也许这会有帮助:@Sahil很棒的帮助谢谢:)@Rumpelstinsk收到了。。现在我明白了,谢谢!它是有效的。。。伟大的解决方案,没有nuget PackagesHanks!它是有效的。。。很好的解决方案,没有nuget包