尝试通过AJAX对我的Web API发出GET请求,仅在Firefox和Chrome中返回401 Unauthorized

时间:2014-01-10 20:38:07

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

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

这是我的jQuery客户端代码,它对我的​​WebAPI进行AJAX调用:

(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 - 任何想法?

2 个答案:

答案 0 :(得分:0)

请将此添加到您的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

答案 1 :(得分:0)

关闭所有Chrome会话,然后尝试使用命令'chrome.exe --disable-web-security --user-data-dir'从cmd(windows)运行Chrome。

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