データベースにデータを送信する ServiceStack を使用して RESTful サービスを構築しました。ローカルでテストしましたが、うまく機能します。サーバーにデプロイして同じコード (jQuery の $.ajax 呼び出し) を実行すると、「アクセスが拒否されました」というエラーが表示されます。here で説明されているように、プラグインを使用して ServiceStack 構成で CORS をセットアップしました。また、ajax 呼び出しで crossDomain を true に設定しました。これを機能させるために他に何をすべきか考えられません。正直なところ、このエラーがどこにスローされているのかわかりません。私はJavascriptをステップ実行しましたが、ajax呼び出しの「失敗」ブロックに到達することさえできず、その前にエラーがスローされます...関連するかどうかをテストするために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 を置き換えました)。
オプション http://servicedomain.com/citations Origin http://callingdomain.com は Access-Control-Allow-Origin で許可されていません。 XMLHttpRequest は http://servicedomain.com//citations を読み込めません。オリジン http://callingdomain.com は Access-Control-Allow-Origin で許可されていません。
しかし、ヘッダーですべてのドメインを明確に許可しています。
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" }
}
});
現在、Chrome のREST コンソール アプリを介して同じサービス コールを実行すると、ServiceStack から有効な応答が得られます。応答ヘッダーは次のとおりです。
ステータスコード: 200 日付: 2013 年 9 月 20 日 (金) 19:54:26 GMT サーバー: Microsoft-IIS/6.0 X-AspNet バージョン: 4.0.30319 X-Powered-By: ASP.NET、ServiceStack/3.948 Win32NT/.NET アクセス制御許可メソッド: POST、GET、OPTIONS、GET、POST、PUT、DELETE、OPTIONS コンテンツ タイプ: アプリケーション/json; 文字セット=utf-8 Access-Control-Allow-Origin: *, * キャッシュ制御: プライベート コンテンツの長さ: 58
だから、純粋なRESTリクエストでは機能するのに、アプリケーションからでは機能しない理由について、私は完全に迷っています??
アップデート:
オンラインで見つけた多くのさまざまなソリューションを試すのに何時間も費やした後、Configure メソッドは次のようになりました。
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 コンソールを使用して引き続き正常に動作しますが、Web ページからメソッドを呼び出して動作させることができないため、少し腹立たしいです。WCF ですべてを書き直す準備がほとんど整っていますが、ローカルで動作することがわかっているため、ServiceStack バージョンを動作させたいと思っています。誰かが私が試すことができる他の提案があれば、私はあなたの助けに感謝します!
更新: 詳細については、下部のコメントを参照してください。IIS の [HTTP ヘッダー] タブからヘッダーを削除する必要がありました。それらをいつ入れたかはわかりませんが、同じ問題に直面する可能性のある他の人のために、IIS のタブのスクリーンショットを次に示します。