在web api 2帖子中,RequestContext.Principal.Identity.Name为空

时间:2015-04-12 15:52:09

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

我是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.") });
            }
        }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

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