问题
I got a problem for a website I was working on. A WebMethod is called from a JavaScript function:
var ajaxOptions = {
url: "/layouts/foobar/Foo.aspx/GetBar"
}
$.ajax(ajaxOptions).done(function(result) {
loadResult(result, a);
});
The method GetBar in Foo.Aspx looks like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetBar()
{
return FoobarManager.GetItems();
}
The function returns a valid JSON object. Sitecore is used in the FoobarManager. Example:
Context.Database.GetItem("/sitecore/content/foobar");
On the development and test environment things ran very smoothly with no problems what so ever. After the deployment to the staging environment I saw that the response of the GetBar function was our custom 404 page. I figured this was because Sitecore was trying to resolve the path "/layouts/foobar/Foo.aspx/GetBar" and failed.
Since it worked on the D and T environment, it must be a configuration problem. I added the GetBar url to the IgnoreUrlPrefixes setting. This resulted in a 500 response in the ajax call: the Sitecore.Context.Database was null. I figured it had something to do with the ItemResolver but I can't understand WHY it worked on D and T but not on A.
What can I do to resolve the url correctly?
回答1:
You have two conflicting things. If you add the /layouts/foobar/Foo.aspx
path to the IgnoreUrlPrefixes
setting which you MUST do (as you did), then Sitecore will not run its context in that. That means, your code Context.Database...
is invalid. I recommend you get the DB by name. Do you need the published "web" DB? You'll need to figure out which one you need but something like this:
var db = Sitecore.Configuration.Factory.GetDatabase("web"); // assumes you need the web DB
var foobar = db.GetItem("/sitecore/content/foobar");
TL;DR: There is no context so you can't get the DB from it.
来源:https://stackoverflow.com/questions/12569554/webmethod-not-accessible-in-sitecore