Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.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
Javascript 来自ASP NET Web API的CORS阻止了Ajax POST调用-对飞行前请求的响应不';无法通过访问控制检查 问题摘要:_Javascript_Asp.net_Ajax_Asp.net Web Api_Cors - Fatal编程技术网

Javascript 来自ASP NET Web API的CORS阻止了Ajax POST调用-对飞行前请求的响应不';无法通过访问控制检查 问题摘要:

Javascript 来自ASP NET Web API的CORS阻止了Ajax POST调用-对飞行前请求的响应不';无法通过访问控制检查 问题摘要:,javascript,asp.net,ajax,asp.net-web-api,cors,Javascript,Asp.net,Ajax,Asp.net Web Api,Cors,我有两个web项目,它们托管在不同的域中。在对我的Web API项目进行ajax调用时,我得到以下信息: CORS已阻止从源“”访问“”处的XMLHttpRequest 策略:对飞行前请求的响应未通过访问控制 检查:上不存在“访问控制允许原点”标题 请求的资源 第一个项目-Web API 我的第一个项目是ASP NET Web API(.NET Framework 4.8) 我在全球范围内为每个人启用了CORS,以确保测试正确通过。 在我的WebApiConfig文件中,我有以下行 confi

我有两个web项目,它们托管在不同的域中。在对我的Web API项目进行ajax调用时,我得到以下信息:

CORS已阻止从源“”访问“”处的XMLHttpRequest 策略:对飞行前请求的响应未通过访问控制 检查:上不存在“访问控制允许原点”标题 请求的资源


第一个项目-Web API 我的第一个项目是ASP NET Web API(.NET Framework 4.8)

我在全球范围内为每个人启用了CORS,以确保测试正确通过。
在我的
WebApiConfig
文件中,我有以下行

config.EnableCors(新的EnableCorsAttribute(“*”、“*”、“*”)

使用System.Web.Http.Cors
以上

我的方法没有什么特殊的属性,因为我们全局启用了CORS

[RoutePrefix(“api/测试”)]
公共类TestController:ApicController
{
[路由(“请求连接”)]
[HttpPost]
公共IHttpActionResult请求连接(MasterOnRequestInputModel inputModel)
{
…这里有一些代码逻辑。。。
}
}

第二个项目-带AJAX请求的JavaScript 我的第二个项目希望在WebAPI中调用上述方法

我的ajax调用如下所示:

$.ajax({
    type: "POST",
    url: myUrl,
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    data: {
        'Body': body,
        'Head': head,
        'Width': width,
        'Height': height
    },
    success: screencastControllerPostSuccess
});
在Chrome中,请求如下所示:

我做错了什么


编辑:

答复 如果你们做到了,正如上面所写的,你们应该对CORS绝对没有问题

我的问题是我们公司正在使用的。WAF拒绝了我的请求,因为这是一次潜在的攻击。这是因为我在请求体中发送HTML元素。我们与我的系统管理员同事一起解决了这个问题

有趣的是,在WAF拒绝我的请求后,它返回一个错误,就好像问题出在CORS上一样。这是因为请求确实是跨域的,但是拒绝请求后的WAF通用响应没有
访问控制允许源

看看的WAF,您会发现很容易处理这样的问题,因为您只需注册OnGuardAction事件,就可以通过调试或将其发送到日志来查看它被阻止的内容和原因

我们这样使用基类FireWallBase来实现这一点

public class MyFireWall : FireWallBase
{
    private readonly ILogger<MyFireWall> _logger;
    private bool _agreeWithFirewall = true;

    public MyFireWall(
        //enable accessing AppConfig
        IConfiguration configuration

        //allow DI to provide interfaces to base class
        , ILoggerFactory? loggerFactory = null, IMemoryCache? memoryCache = null
        , IIncidentDatabase? incidentDatabase = null, IWhoisRepository? whoisRepository = null, ISubscriptionsRepository? subscriptions = null
        , IEmailReportDesination? emailReportDesination = null, IDatabaseReportDestination? databaseReportDestination = null
        , ILoggerReportDesination? loggerReportDestination = null, IFireWallDiskLoggerDestination? diskLoggerDestination = null
        , IEventLogReporting? eventLogReporting = null, IGeoFactory? geoFactory = null, ILatLongRepository? latLongRepository = null
        , IResetRepository? resetRepository = null)
        : base(loggerFactory, memoryCache, incidentDatabase, whoisRepository, subscriptions, emailReportDesination, databaseReportDestination
              , loggerReportDestination, diskLoggerDestination, eventLogReporting, geoFactory, latLongRepository, resetRepository)
    {
        var section = configuration.GetSection("FireWall");
        if (section.Exists())
        {
            _isReccommendOnly = section.GetValue<bool>("AgreeWithFirewall");
        }
        base.Trigger_OnFireWallCreated(this);
        OnIncident += MyFireWall_OnIncident;
        OnGuardAction += MyFireWall_OnGuardAction;
        OnUserTypeChange += MyFireWall_OnUserTypeChange;
        _logger = loggerFactory.CreateLogger<MyFireWall>();
    }


    private void MyFireWall_OnUserTypeChange(object? sender, Walter.Web.FireWall.EventArguments.UserTypeChangedEventArgs e)
    {
        _logger?.LogCritical("{oldType} : {newType}\n   {route}\n   Rules:\n   {data}"
            , e.OriginalType
            , e.NewType
            , e.Rout
            , string.Join("\n   ", e.Rules)
            );

        //allow the change
        e.Allow = true;

        if (e.OriginalType.HasFlag(UserTypes.IsSearchEngine) && e.NewType.HasFlag(UserTypes.IsMalicious))
        {
            //remove the malicious flag from search engines to not prevent search engines from 
            //indexing the site
            e.NewType &= ~UserTypes.IsMalicious;
        }
    }

    private void MyFireWall_OnGuardAction(object? sender, Walter.Web.FireWall.EventArguments.GuardActionEventArgs e)
    {
        _logger?.LogCritical("{Method} {page} : {route}\n   {action}:{RuleNr}\n   Reasons:{Reason}\n   {data}"
            , e.Page.Method
            , e.Page.OriginalUrl.AbsolutePath
            , e.Page.FireWallRoute
            , e.Action
            , string.Join("\n   ", e.Page.PageViolationStack.Select(s => s.ToString()))
            );

        //allow the firewall to block requests
        e.Allow = _agreeWithFirewall;
    }

    private void MyFireWall_OnIncident(object? sender, Walter.Web.FireWall.EventArguments.FireWallIncidentEventArgs e)
    {
        _logger?.LogCritical("{Method} {page} : {route}\n   {rule}:{RuleNr}\n   Reasons:{Reason}\n   {data}"
            , e.Page.Method
            , e.Page.OriginalUrl.AbsolutePath
            , e.Page.FireWallRoute
            , e.StackEntry.Rule
            , e.StackEntry.RuleNr
            , e.StackEntry.Reason
            , string.Join("\n   ", e.Data.Select(s => $"{s.Key}:{s.Value}"))
            );
        //allow the firewall to raise incidents
        e.Allow = _agreeWithFirewall;
    }
}
公共类MyFireWall:FireWallBase { 专用只读ILogger\u记录器; 私有bool_agreeWithFirewall=true; 公共MyFireWall( //启用访问AppConfig i配置配置 //允许DI向基类提供接口 ,ILoggerFactory?loggerFactory=null,IMemoryCache?memoryCache=null ,IIncidentDatabase?incidentDatabase=null,IWhoisRepository?whoisRepository=null,iSubscriptionRepository?subscriptions=null ,IEMailReportDesiation?EmailReportDesiation=null,IDatabaseReportDestination?databaseReportDestination=null ,iLoggerReportDestination?loggerReportDestination=null,IFireWallDiskLoggerDestination?diskLoggerDestination=null ,IEventLogReporting?eventLogReporting=null,IGeoFactory?geoFactory=null,ILatLongRepository?latLongRepository=null ,IResetRepository?resetRepository=null) :base(loggerFactory、memoryCache、incidentDatabase、whoisRepository、订阅、EmailReportDesiation、databaseReportDestination ,loggerReportDestination,diskLoggerDestination,eventLogReporting,geoFactory,latLongRepository,resetRepository) { var section=configuration.GetSection(“防火墙”); if(section.Exists()) { _isReccommendOnly=section.GetValue(“AgreeWithFirewall”); } base.Trigger_OnFireWallCreated(此); OnIncident+=我的防火墙\u OnIncident; OnGuardAction+=MyFireWall\u OnGuardAction; OnUserTypeChange+=MyFireWall\u OnUserTypeChange; _logger=loggerFactory.CreateLogger(); } 私有void MyFireWall\u OnUserTypeChange(对象?发送方,Walter.Web.FireWall.EventArguments.UserTypeChangedEventArgs e) { _logger?.LogCritical({oldType}:{newType}\n{route}\n规则:\n{data}” ,e.原始类型 ,e.NewType ,e.Rout ,string.Join(“\n”,e.Rules) ); //允许改变 e、 允许=真; if(e.OriginalType.HasFlag(UserTypes.issearchanine)和&e.NewType.HasFlag(UserTypes.IsMalicious)) { //从搜索引擎中删除恶意标志以不阻止搜索引擎 //为网站编制索引 e、 NewType&=~UserTypes.IsMalicious; } } 私有void MyFireWall\u OnGuardAction(对象?发件人,Walter.Web.FireWall.EventArguments.GuardActionEventArgs e) { _logger?.LogCritical({Method}{page}:{route}\n{action}:{RuleNr}\n原因:{Reason}\n{data} ,e.Page.Method ,e.Page.OriginalUrl.AbsolutePath ,e.Page.FireWallRoute ,e.行动 ,string.Join(“\n”,e.Page.PageViolationStack.Select(s=>s.ToString())) ); //允许防火墙阻止请求 e、 允许=_同意防火墙; } 私有void MyFireWall\u OnIncident(对象?发送方,Walter.Web.FireWall.EventArguments.FireWallIncidentEventArgs e) { _logger?.LogCritical({Method}{page}:{route}\n{rule}:{RuleNr}\n原因:{Reason}\n{data} ,e.Page.Method ,e.Page.OriginalUrl.AbsolutePath ,e.Page.FireWallRoute ,e.StackEntry.Rule ,e.StackEntry.RuleNr ,e.StackEntry.Reason ,string.Join(“\n”,e.Data.Select(s=>$”{s.Key}:{s
services.AddFireWall<MyFireWall>("Token", "Key", new Uri(Configuration["domainUri"], UriKind.Absolute), options =>{
         //add your options here
       });