使用 jquery 调用 webmethod 时出现“401 Unauthorized”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2297856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting "401 Unauthorized" error consistently with jquery call to webmethod
提问by CareMatch
I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
我一直在努力让我的 jquery 调用 webmethod 工作。我被服务器退回了“401 Unauthorized”响应。我必须在 web.config 或其他地方有一个不正确的设置,这会阻止成功调用。
Your insight is appreciated!
感谢您的洞察力!
Call to js function the invokes the jquery call
调用 js 函数调用 jquery 调用
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
进行 jquery 调用的 JavaScript 函数
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
网页中的网页方法
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
在 Firebug 控制台中看到的响应
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
和
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
我已经查看并阅读了有关该主题的常用网站(Encosia 等),但还是有用的。要么我遗漏了一个关键部分,要么我的环境的安全参数中有一些微妙之处阻止了呼叫。
Here are some other potentially useful tidbits that may impact your diagnosis:
以下是一些可能会影响您的诊断的其他潜在有用的花絮:
- Webmethods in codebehind
- Using Sitecore CMS (Does not seem to intefere, never know)
- IIS7
- .NET 3.5
- jQuery 1.3.2
- 代码隐藏中的 Webmethods
- 使用 Sitecore CMS(似乎不影响,永远不知道)
- IIS7
- .NET 3.5
- jQuery 1.3.2
I look forward to your insights and direction--thank you!
我期待您的见解和指导——谢谢!
采纳答案by CareMatch
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
是的,它确实开始工作了!由于 Sitecore CMS 确实执行 URL 重写以生成友好的 URL(它动态地将页面组合成层,类似于母版页的概念),我想到它可能会导致一些问题,最初导致 401 错误。我通过使用单个 ASPX 创建一个单独的项目来验证这一点——并且通过一些工作,我能够调用 Web 方法并使用 jquery 获取值。然后,我在我的 Web 根目录中创建了几乎相同的 ASPX,但告诉 Sitecore 在向它发出请求时忽略它(web.config 中的 IgnoreUrlPrefixes),经过一些工作后,我也能够使其成功运行!谢谢你的帮助。
回答by John Lewin
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
Firebug 控制台的 json 响应提供了最有说服力的线索 IMO。System.InvalidOperationException(奇怪地依赖于 401 响应)表明还有更多的东西在起作用。
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
首先,谷歌搜索“InvalidOperationException webmethod jquery”返回建议序列化问题可能引发此异常的文章。要排除这种情况,请暂时将“data: paramList”更改为“data: '{}'”。此外,附加调试器并查看异常是否在方法执行之前或之后发生并尝试序列化结果。
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
如果上述步骤为空,您可能需要尝试重置为干净的 web.config 或阅读更多从“InvalidOperationException webmethod”搜索返回的结果
回答by Punit Vora
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
您使用什么形式的身份验证(如果有)?首先想到的是确保您在 IIS 中的 webApp 设置为允许匿名用户(如果您确实希望以匿名用户身份进行调用)。此外,您在 web.config 中的身份验证模式没有错误地设置为 Windows。如果您不能允许匿名用户并且正在使用表单身份验证,则用户必须先登录,然后才能从您的页面进行此调用。
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
如果上述设置正确,则尝试从服务器端定期调用服务,以确保无论服务调用点如何,问题都是一致的。
Post more settings if the problem is not resolved. Hope this helps.
如果问题没有解决,请发布更多设置。希望这可以帮助。