gpt4 book ai didi

javascript - 向 ServiceStack RESTful 服务发送数据,得到 'Access is denied'

转载 作者:行者123 更新时间:2023-11-30 17:51:28 37 4
gpt4 key购买 nike

我使用 ServiceStack 构建了一个 RESTful 服务,该服务将数据发送到数据库。我在本地测试过,效果很好。当我将它部署到服务器并运行相同的代码(即 jQuery $.ajax 调用)时,我收到“访问被拒绝”错误。我在我的 ServiceStack 配置中使用插件作为 explained here 设置了 CORS .我还在我的 ajax 调用中将 crossDomain 设置为 true 。我想不出还有什么办法可以让它工作,老实说,我不确定这个错误是在哪里抛出的。我已经逐步执行了 Javascript,它甚至没有到达 ajax 调用的“失败” block ,错误在此之前抛出...我正在使用 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):

OPTIONS http://servicedomain.com/citations Origin http://callingdomain.com is not allowed by Access-Control-Allow-Origin.XMLHttpRequest cannot load http://servicedomain.com//citations. Origin http://callingdomain.com is not allowed by Access-Control-Allow-Origin.

But I am clearly allowing all domains in my headers:

            Plugins.Add(new CorsFeature()); //Enable CORS

SetConfig(new EndpointHostConfig {
DebugMode = true,
AllowJsonpRequests = true,
WriteErrorsToResponse = true,
GlobalResponseHeaders =
{
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }
}
});

现在,如果我通过 REST Console app 运行相同的服务调用在 Chrome 中,我从 ServiceStack 得到了有效的响应。这是响应 header :

Status Code: 200Date: Fri, 20 Sep 2013 19:54:26 GMTServer: Microsoft-IIS/6.0X-AspNet-Version: 4.0.30319X-Powered-By: ASP.NET, ServiceStack/3.948 Win32NT/.NETAccess-Control-Allow-Methods: POST,GET,OPTIONS, GET, POST, PUT, DELETE, OPTIONSContent-Type: application/json; charset=utf-8Access-Control-Allow-Origin: *, *Cache-Control: privateContent-Length: 58

So I'm totally lost as to why it works in a pure REST request, but not from the application??

Update:

After spending many hours trying many different solutions I've found online, my Configure method now looks like this:

        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);
}
}

此时我不确定该怎么做。我已经尝试了所有方法,但仍然遇到相同的错误。使用 Chrome 中的 REST 控制台,这些方法继续正常工作,这有点令人恼火,因为我永远无法让它们工作,从网页调用它们。我几乎准备好用 WCF 重写整个东西,但我真的很想让 ServiceStack 版本工作,因为我知道它在本地工作!如果有人有任何其他建议我可以尝试,我将非常感谢您的帮助!

更新:详情见底部评论。我不得不从 IIS 的 HTTP header 选项卡中删除 header 。不确定我何时将它们放入,但对于可能遇到相同问题的任何其他人,这里是 IIS 中选项卡的屏幕截图:

Custom Http Headers

最佳答案

我和你有同样的问题,在我之前的question

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

我在 AppHost 中使用的代码

          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
}

和你一样用 JavaScript

  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);
}
});
}

关于javascript - 向 ServiceStack RESTful 服务发送数据,得到 'Access is denied',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923930/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com