【问题标题】:RequestContext.Principal.Identity.Name is empty in web api 2 postWeb api 2 帖子中的 RequestContext.Principal.Identity.Name 为空
【发布时间】:2015-06-17 22:32:19
【问题描述】:

我是 web api 的新手,在我的 post 方法中获取登录用户的名称时似乎遇到了问题。我正在使用

RequestContext.Principal.Identity.Name

但是,这似乎只返回一个空字符串。它在我的 get 方法中运行良好,但在帖子中却不行。这是我的整个方法

[Route("receive")]
        [HttpPost]
        public HttpResponseMessage Receive(PostmarkInboundMessage message)
        {
            if (message != null)
            {
                // To access message data
                var headers = message.Headers ?? new List<Header>();

                // To access Attachments
                if (message.Attachments != null)
                {
                    var attachments = message.Attachments;

                    var c = new CVService();
                    var user = string.IsNullOrEmpty(RequestContext.Principal.Identity.Name) ? "unknown" : RequestContext.Principal.Identity.Name;

                    c.UpdateLog(user);

                    foreach (var attachment in attachments)
                    {
                        // Access normal members, etc
                        var attachmentName = attachment.Name;

                        // To access file data and save to c:\temp\
                        //if (Convert.ToInt32(attachment.ContentLength) > 0)
                        //{
                        //    byte[] filebytes = Convert.FromBase64String(attachment.Content);
                        //    var fs = new FileStream(attachmentSaveFolder + attachment.Name,
                        //                                   FileMode.CreateNew,
                        //                                   FileAccess.Write,
                        //                                   FileShare.None);
                        //    fs.Write(filebytes, 0, filebytes.Length);
                        //    fs.Close();
                        //}
                    }
                }

                // If we succesfully received a hook, let the call know
                return new HttpResponseMessage(HttpStatusCode.Created);    // 201 Created
            }
            else
            {
                // If our message was null, we throw an exception
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Error parsing Inbound Message.") });
            }
        }

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api asp.net-web-api2


    【解决方案1】:

    确保在 GET 和 POST 方法中发送标头(令牌),并且在这两种方法或控制器本身中设置 [Authorize] 过滤器,以便您如果没有发送令牌,将被拒绝

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 2017-06-15
      • 2018-03-29
      • 2020-03-28
      • 2022-12-21
      • 1970-01-01
      相关资源
      最近更新 更多