【问题标题】:Trying to make a GET request via AJAX against my WebAPI, returns 401 Unauthorized only in Firefox and Chrome尝试通过 AJAX 对我的 WebAPI 发出 GET 请求,仅在 Firefox 和 Chrome 中返回 401 Unauthorized
【发布时间】:2014-01-29 23:53:44
【问题描述】:

我只是向我的 WebAPI 方法发出 AJAX GET 请求 - IE 很好,但 Chrome 和 Firefox 返回 401 Unauthorized 错误。

这是我的 jQuery 客户端代码,它使 AJAX 调用我的 WebAPI:

(function ($) {
    $.displayToastrNotifications = function (appId) {
        $.support.cors = true;
        var userId = '';

        // get current user's ID
        $.ajax({
            url: 'http://server/AppTools/API/Identity/GetCurrentlyLoggedInUserId',
            type: 'GET',
            dataType: 'text',
            crossDomain: true,
            success: function (data) {
                userId = data;
                // get all messages for the app
                $.ajax({
                    url: 'http://server/AppToolsWS/api/BulletinBoard/GetMessagesForApp/' + appId,
                    type: 'GET',
                    dataType: 'json',
                    crossDomain: true,
                    success: function (data) {
                        DisplayToasterNotifications(data);
                    },
                    error: function (x, y, z) {
                        alert('getmessagesforapp: ' + x + '\n' + y + '\n' + z);
                    }
                });
            },
            error: function (x, y, z) {
                alert('getuserid: ' + x + '\n' + y + '\n' + z);
            }
        });
...

这是我的 WebAPI 方法:

[EnableCors("*", "*", "*")]
public class IdentityController : ApiController
{
    [HttpGet]
    public HttpResponseMessage GetCurrentlyLoggedInUserId()
    {
        var userid = string.Empty;
        try
        {
            userid = HelperClasses.StringHelper.GetLogonUserID();
        }
        catch (Exception ex)
        {

        }

        return this.Request.CreateResponse(HttpStatusCode.OK, userid, "text/plain");
    }
}

我可以在任何浏览器中手动导航到此方法,它会成功返回数据。很奇怪,我不知道为什么它会在 Firefox 和 Chrome 中这样做——我在使用 AD 的公司内部网上——有什么想法吗?

【问题讨论】:

  • 您的 IIS 网站是否使用 Windows 安全性?
  • 它在我公司的网络服务器上 - 我不知道。

标签: javascript jquery ajax google-chrome asp.net-web-api


【解决方案1】:

请将此添加到您的 web.config 中

<location path="api">
    <system.web>
        <authorization>
            <allow users="*"/>
        </authorization>
    </system.web>
</location> 

您可以在此处找到更多信息:

http://msdn.microsoft.com/en-us/library/wce3kxhd%28v=vs.100%29.aspx

Disable Windows Authentication for WebAPI

【讨论】:

  • 您不能使用路由或 web.config 文件来保护您的 MVC 应用程序。保护 MVC 应用程序的唯一受支持的方法是使用具有 [Authorize] 属性的基类,然后让每个控制器类型子类化该基类型。 - 每个 MSDN
【解决方案2】:

关闭 Chrome 的所有会话并尝试使用命令“chrome.exe --disable-web-security --user-data-dir”从 cmd (windows) 运行 Chrome。

如果您正确操作,Chrome 会发出警告标题:“您使用的是不受支持的命令行标志:--disable-web-security。稳定性和安全性将受到影响”。

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多