我有一个 WCF 服务(该项目是一个 WCF 服务库),该服务有效,我可以从 Insomnia 中调用此服务,但是当我尝试在 next.js 应用程序中使用它时,出现此错误:
从源“http://localhost:3000”获取“http://miURL”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:无“Access-Control-Allow-” Origin' 标头存在于所请求的资源上。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我知道这是一个 CORS 问题,但我不知道如何在我的 WCF 服务中启用 CORS。
这是我的代码:
JavaScript:
const test = async () => {
const peticion = await fetch('URL', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
})
const respuesta = await peticion.json()
console.log(respuesta);
}
我的服务代码:
public class Service1 : IService1
{
public string leerHuella()
{
Form1 form1 = new Form1();
string value = form1.leerHuellaForm();
return value;
}
}
我的iService代码:
public interface IService1
{
[OperationContract]
[WebGet]
string leerHuella();
}
我的应用程序配置:
<endpointBehaviors>
<behavior name="jsonBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
如果有人可以帮助我,那就太好了
我已经尝试了各种教程机器人中的一些配置,到目前为止还没有成功。 请注意,我没有 asax.cs 文件,并且无法添加文件,该选项在我的添加项目窗口中不可用。
您可以尝试这个解决方案:
添加两个新文件,Global.asax和Global.asax.cs
全球.asax:
<%@ Application Codebehind="Global.asax.cs" Inherits="Wcf.Global" Language="C#" %>
Global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace Wcf
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
//HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "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();
}
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
您可以参考这个文档: 在 WCF 中启用 CORS