2015-04-12 65 views
5

我是新來的web api,並且我似乎遇到了在我的post方法中獲取登錄用戶名的問題。我使用RequestContext.Principal.Identity.Name在web api 2中是空的

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

任何幫助將不勝感激。

回答

0

確保您發送頭(令牌)在這兩種方法GET和POST並且還設置[授權]過濾器在兩種方法或控制器本身,所以如果令牌是不是你會被拒絕發送