Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.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 将数据发送到ServiceStack RESTful服务,获取';访问被拒绝';_Javascript_Jquery_Ajax_Rest_<img Src="//i.stack.imgur.com/WM7S8.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">servicestack - Fatal编程技术网 servicestack,Javascript,Jquery,Ajax,Rest,servicestack" /> servicestack,Javascript,Jquery,Ajax,Rest,servicestack" />

Javascript 将数据发送到ServiceStack RESTful服务,获取';访问被拒绝';

Javascript 将数据发送到ServiceStack RESTful服务,获取';访问被拒绝';,javascript,jquery,ajax,rest,servicestack,Javascript,Jquery,Ajax,Rest,servicestack,我用ServiceStack构建了一个RESTful服务,它将数据发送到数据库。我在本地测试过,效果很好。当我将它部署到服务器并运行相同的代码(jQuery$.ajax调用)时,我得到一个“访问被拒绝”错误。我在ServiceStack配置中使用插件as设置了CORS。在ajax调用中,我还将crossDomain设置为true。我想不出还能做些什么来让它工作,老实说,我也不确定这个错误会被抛出到哪里。我已经浏览了Javascript,但它甚至没有到达ajax调用的“failure”块,在此之前

我用ServiceStack构建了一个RESTful服务,它将数据发送到数据库。我在本地测试过,效果很好。当我将它部署到服务器并运行相同的代码(jQuery$.ajax调用)时,我得到一个“访问被拒绝”错误。我在ServiceStack配置中使用插件as设置了CORS。在ajax调用中,我还将crossDomain设置为true。我想不出还能做些什么来让它工作,老实说,我也不确定这个错误会被抛出到哪里。我已经浏览了Javascript,但它甚至没有到达ajax调用的“failure”块,在此之前会抛出错误。。。我正在使用IE9进行测试,如果相关的话

知道会发生什么吗

以下是我的ServiceStack POST方法:

    public CitationResponse Post(Citation citation)
    {
        var response = new CitationResponse { Accepted = false };

        if (string.IsNullOrEmpty(citation.ReportNumber))
        {
            response.Accepted = false;
            response.Message = "No data sent to service.  Please enter data in first.";
            return response;
        }

        try
        {
            response.ActivityId = Repository.CreateCitation(citation.ReportNumber, citation.ReportNumber_Prefix, citation.ViolationDateTime, citation.AgencyId, citation.Status);
            response.Accepted = true;
        }
        catch (Exception ex)
        {
            response.Accepted = false;
            response.Message = ex.Message;
            response.RmsException = ex;
        }

        return response;
    }
下面是调用web服务的Javascript函数:

   SendCitationToDb: function(citation, callback) {
        $.ajax({
            type: "POST",
            url: Citations.ServiceUrl + "/citations",
            data: JSON.stringify(citation),
            crossDomain: true,
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                if (!data.Accepted) {
                    Citations.ShowMessage('Citation not added', 'Citation not added to database.  Error was: ' + data.Message, 'error');
                } else {
                    citation.ActivityId = data.ActivityId;
                    callback(data);
                }
            },
            failure: function(errMsg) {
                Citations.ShowMessage('Citation not added', 'Citation not added to database.  Error was: ' + errMsg.Message, 'error');
            }
        });
    }
谢谢你的帮助

更新: 我刚刚在Chrome 29上运行了相同的应用程序,我发现了以下错误(为了安全起见,替换了真实的URL):

现在,如果我在Chrome中运行相同的服务调用,我将从ServiceStack获得有效响应。以下是响应标题:

Status Code: 200 Date: Fri, 20 Sep 2013 19:54:26 GMT Server: Microsoft-IIS/6.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET, ServiceStack/3.948 Win32NT/.NET Access-Control-Allow-Methods: POST,GET,OPTIONS, GET, POST, PUT, DELETE, OPTIONS Content-Type: application/json; charset=utf-8 Access-Control-Allow-Origin: *, * Cache-Control: private Content-Length: 58 身份代码:200 日期:2013年9月20日星期五19:54:26 GMT 服务器:Microsoft IIS/6.0 X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET,ServiceStack/3.948 Win32NT/.NET 访问控制允许方法:POST、GET、OPTIONS、GET、POST、PUT、DELETE、OPTIONS 内容类型:application/json;字符集=utf-8 访问控制允许源代码:** 缓存控制:专用 内容长度:58 所以我完全不明白为什么它在纯REST请求中工作,而不是在应用程序中工作

更新:

在花了很多时间尝试我在网上找到的许多不同的解决方案后,我的配置方法现在如下所示:

        public override void Configure(Container container)
        {
            SetConfig(new EndpointHostConfig
            {
                DefaultContentType = ContentType.Json,
                ReturnsInnerException = true,
                DebugMode = true, //Show StackTraces for easier debugging (default auto inferred by Debug/Release builds)
                AllowJsonpRequests = true,
                ServiceName = "SSD Citations Web Service",
                WsdlServiceNamespace = "http://www.servicestack.net/types",
                WriteErrorsToResponse = true,
                GlobalResponseHeaders = 
                { 
                    { "Access-Control-Allow-Origin", "*" },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }
                }
            });

            container.RegisterAutoWired<Citation>();
            container.RegisterAutoWired<Driver>();
            container.RegisterAutoWired<Vehicle>();
            container.RegisterAutoWired<Violations>();

            using (var getAttributes = container.Resolve<AttributesService>())
                getAttributes.Get(new AttributesQuery());

            Plugins.Add(new CorsFeature());
            RequestFilters.Add((httpReq, httpRes, requestDto) =>
            {
                httpRes.AddHeader("Access-Control-Allow-Origin", "*");
                httpRes.AddHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS");
                httpRes.AddHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");

                if (httpReq.HttpMethod == "OPTIONS")
                    httpRes.EndServiceStackRequest(); //   extension method
            });

            Routes
              .Add<Attribute>("/attributes", "GET, OPTIONS")
              .Add<Citation>("/citations", "POST, GET, OPTIONS, DELETE")
              .Add<Driver>("/driver", "POST, OPTIONS")
              .Add<Vehicle>("/vehicle", "POST, OPTIONS")
              .Add<Violations>("/violations", "POST, OPTIONS");

            var config = new AppConfig(new ConfigurationResourceManager());
            container.Register(config);
        }
    }
public override void Configure(容器)
{
SetConfig(新端点主机配置)
{
DefaultContentType=ContentType.Json,
returnRexception=true,
DebugMode=true,//显示堆栈跟踪以便于调试(默认情况下由调试/发布版本自动推断)
AllowJsonpRequests=true,
ServiceName=“SSD引文Web服务”,
WsdlServiceNamespace=”http://www.servicestack.net/types",
WriteErrorStoreResponse=true,
全球负责人=
{ 
{“访问控制允许来源”,“*”},
{“访问控制允许方法”、“获取、发布、放置、删除、选项”}
}
});
container.RegisterAutoWired();
container.RegisterAutoWired();
container.RegisterAutoWired();
container.RegisterAutoWired();
使用(var getAttributes=container.Resolve())
getAttributes.Get(新属性查询());
Add(newcorsfeature());
Add((httpReq、httpRes、requestDto)=>
{
AddHeader(“访问控制允许源代码”、“*”);
AddHeader(“访问控制允许方法”、“发布、获取、删除、选项”);
AddHeader(“访问控制允许头”,“X请求的,内容类型”);
如果(httpReq.HttpMethod==“选项”)
httpRes.EndServiceStackRequest();//扩展方法
});
路线
.Add(“/attributes”,“GET,OPTIONS”)
.Add(“/引用”,“发布,获取,选项,删除”)
.Add(“/driver”,“POST,OPTIONS”)
.添加(“/vehicle”、“POST、OPTIONS”)
.添加(“/违规”、“张贴、选项”);
var config=new-AppConfig(new-ConfigurationResourceManager());
container.Register(config);
}
}
现在我不知道该怎么办。我什么都试过了,但还是会犯同样的错误。使用Chrome中的REST控制台,这些方法仍然工作得很好,这有点令人恼火,因为我无法让它们在网页上调用它们。我几乎准备好用WCF重新编写整个过程,但我真的很想让ServiceStack版本正常工作,因为我知道它在本地工作!如果有人有任何其他建议我可以尝试,我将非常感谢你的帮助

更新: 有关详细信息,请参见底部的注释。我必须从IIS中的HTTP标题选项卡中删除标题。我不确定我什么时候把它们放进去,但对于其他可能面临同样问题的人,这里是IIS中选项卡的屏幕截图:


在我之前的工作中,我和你有同样的问题

您可以阅读mythz和的非常有用的答案

我在AppHost中使用的代码

          using System.Web;
          using ServiceStack.WebHost.Endpoints.Extensions;  // for  httpExtensions methods  
    //  => after  v.3.9.60,  =>using ServiceStack;


谢谢你的回复。在过去的几天里,我尝试了你的建议,以及其他一些推荐的修复方法,但仍然得到了最初问题中提到的相同错误。IE显示访问被拒绝,Chrome显示我的主叫域“不被访问控制允许来源所允许。*”完全不明白这为什么不起作用。我让另一个开发者看了看,我们在周五和今天都花了几个小时,但仍然没有运气。它在本地工作,部署时不工作。如果我直接在REST控制台中进行服务调用,它们就可以工作,但不是通过jQueryAjax调用。Eddie,上面的代码在生产环境中工作。作为一个单独的示例,您尝试过吗?除非我在复制粘贴上犯了错误,否则它应该可以正常工作。今天早上我花时间用您的代码构建了一个测试项目,将它部署到同一台服务器上,结果成功了。所以我开始并排比较项目,看看有什么不同。代码中的所有内容看起来都一样。最后,我远程访问了服务器,打开了这两个站点的属性,发现“HTTP头”选项卡中的“自定义HTTP头”列出了相同的头。我把它们拿走了,罪恶
        public override void Configure(Container container)
        {
            SetConfig(new EndpointHostConfig
            {
                DefaultContentType = ContentType.Json,
                ReturnsInnerException = true,
                DebugMode = true, //Show StackTraces for easier debugging (default auto inferred by Debug/Release builds)
                AllowJsonpRequests = true,
                ServiceName = "SSD Citations Web Service",
                WsdlServiceNamespace = "http://www.servicestack.net/types",
                WriteErrorsToResponse = true,
                GlobalResponseHeaders = 
                { 
                    { "Access-Control-Allow-Origin", "*" },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }
                }
            });

            container.RegisterAutoWired<Citation>();
            container.RegisterAutoWired<Driver>();
            container.RegisterAutoWired<Vehicle>();
            container.RegisterAutoWired<Violations>();

            using (var getAttributes = container.Resolve<AttributesService>())
                getAttributes.Get(new AttributesQuery());

            Plugins.Add(new CorsFeature());
            RequestFilters.Add((httpReq, httpRes, requestDto) =>
            {
                httpRes.AddHeader("Access-Control-Allow-Origin", "*");
                httpRes.AddHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS");
                httpRes.AddHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");

                if (httpReq.HttpMethod == "OPTIONS")
                    httpRes.EndServiceStackRequest(); //   extension method
            });

            Routes
              .Add<Attribute>("/attributes", "GET, OPTIONS")
              .Add<Citation>("/citations", "POST, GET, OPTIONS, DELETE")
              .Add<Driver>("/driver", "POST, OPTIONS")
              .Add<Vehicle>("/vehicle", "POST, OPTIONS")
              .Add<Violations>("/violations", "POST, OPTIONS");

            var config = new AppConfig(new ConfigurationResourceManager());
            container.Register(config);
        }
    }
          using System.Web;
          using ServiceStack.WebHost.Endpoints.Extensions;  // for  httpExtensions methods  
    //  => after  v.3.9.60,  =>using ServiceStack;
          public override void Configure(Container container)
          {   

                SetConfig(new ServiceStack.WebHost.Endpoints.EndpointHostConfig
                {
                 DefaultContentType = ContentType.Json,
                  ReturnsInnerException = true,
                  WsdlServiceNamespace = "http://www.servicestack.net/types"
                });

             Plugins.Add(new CorsFeature()); 
             this.RequestFilters.Add((httpReq, httpRes, requestDto) =>
             {
                //Handles Request and closes Responses after emitting global HTTP Headers
                   if (httpReq.HttpMethod == "OPTIONS")
                           httpRes.EndServiceStackRequest();  //httpExtensions method
               //  =>after  v.3.9.60, => httpRes.EndRequestWithNoContent(); 
              });

            Routes
             .Add<TestRequest>("/TestAPI/Reservation", "POST, OPTIONS");   // OPTIONS is mandatory for CORS
          }
  jQuery.support.cors = true;

    function TestRequestCall() {
       var  TestRequest = new Object();                
           TestRequest.Id = 11111;
           TestRequest.City = "New York";



      $.ajax({
          type: 'Post',
          contentType: 'application/json',         
          url: serverIP +'/TestAPI/Reservation',
          data: JSON.stringify( TestRequest ),
          dataType: "json",
          success: function (TestResponse, status, xhr) {

                 if(TestResponse.Accepted)  doSomething();

           },
           error: function (xhr, err) {
              alert(err);
           }
      });
   }