尽管已调用API,但Angularjs响应仍失败,并且返回成功

时间:2020-08-03 06:33:30

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

所以我有这个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的屏幕截图: enter image description here

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

1 个答案:

答案 0 :(得分:0)

代替

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 属性以供进一步使用。