【问题标题】:Angularjs response failed eventhough the API is called and return success即使调用 API 并返回成功,Angularjs 响应也会失败
【发布时间】:2020-11-23 05:50:43
【问题描述】:

所以我有这个 API 从域中获取用户名,该 API 使用 C#

    [HttpGet]
    [Route("api/authenticate")]
    public HttpResponseMessage getWinUser()
    {
        try
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
            UserPrincipal user = UserPrincipal.Current;
            string displayName = user.DisplayName;

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new ObjectContent<string>(displayName, Configuration.Formatters[0]);
            return response;
        }
        catch (Exception e)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
        }
    }

我有使用 AngularJS 调用它的方法

function getUserData() {
       return $http({
          url: 'https://localhost:44363/api/authenticate',
          method: 'GET',
          //withCredentials: true,
          headers: {
            'Content-Type': 'application/json; charset=utf-8',
          }
       });
 }

这就是我感到困惑的地方。 API 的方法调用返回了我的预期。从 Postman 调用端点也会返回我需要的内容。并且直接从端点链接调用也按预期返回。 但是,当我从 Chrome 浏览器调用函数时,它返回为 ERR:FAILED

这是来自 Chrome 的屏幕截图:

我做错了什么,我应该使用什么?

【问题讨论】:

  • ObjectContent 是否有可能返回常规字符串而您正在等待 JSON?
  • 嗨 DA,javascript 返回函数不接受任何类型的返回吗?函数调用是return getUserData().then(function (response) {
  • 我看到标题中想要的数据是application/json。

标签: c# angularjs http asp.net-web-api xmlhttprequest


【解决方案1】:

而不是

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new ObjectContent<string>(displayName, Configuration.Formatters[0]);
        return response;
                                                                                     

你可以在下面使用吗:-

return Request.CreateResponse(HttpStatusCode.OK,new { displayName= user.DisplayName });

然后您可以在成功处理程序中解析 response.displayname 属性以供进一步使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2015-01-07
    • 2014-11-17
    • 2013-11-07
    • 2023-03-15
    • 2014-09-07
    • 1970-01-01
    相关资源
    最近更新 更多