web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Dynamics 365 API View response createdBy value return userId instead of userName

(0) ShareShare
ReportReport
Posted on by

Hi, please help.

I have a json response from https://[root]/api/data/v9.0/[entities]?savedQuery=[viewId] There's a column of createdby in the view.

In the response, the createdBy key returns "_createdby_value": "blabla-blabla-blalalajfd75849325", but I want to have the user name instead. I also tried with ownerId etc, but seems there are all fields with ids.

Is there a way I could get the actual username and save in my own json object please?

Thank you very much. 

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hello,

    You are looking to include 'Formatted Values', which is what the record name is. Similarly to returning the names of OptionSets values, instead of just the integer.

     

    You can accomplish this by adding this header to your request:

    Prefer: odata.include-annotations="*"

    Reference: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/query-data-web-api#retrieve-data-about-lookup-properties (see section 'Retrieve data about lookup properties')

  • Verified answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    You need to use the following to return the actual value:

    var createdByName = results["_createdby_value@OData.Community.Display.V1.FormattedValue"];

    Make sure to add the following line of code in your request (assuming your request variable is called request):

    request.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");

    or

    request.setRequestHeader("Prefer", "odata.include-annotations=*");

    Hope this helps.

  • Community Member Profile Picture
    on at

    Hi Michel and Aric,

    Thanks for helping again. I tried the approach you and Aric proposed.

    In the request header, I added

    retrieveRequest.Headers.Add("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");

    When construct my response object, I did a small test of

    if (attributeName.Equals("_createdby_value"))

                                       {

                                           var temp = dataEntry["_createdby_value@OData.Community.Display.V1.FormattedValue"];

                                       }

    -------------------------------------------------------------------------------------------------------------------------------------

    But above gave me error of "HttpMessageInvoker.cs not found: error when tracing through it, and in the final response gives

    {

    Message: "An error has occurred.",

    ExceptionMessage: "The given key was not present in the dictionary.",

    ExceptionType: "System.Collections.Generic.KeyNotFoundException",

    StackTrace: " at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"

    }

    Do you spot anyplace I missed please? Thanks again.

  • Community Member Profile Picture
    on at

    I double checked my request, the header of "Prefer" is added.

    But in the raw response, the "_createdBy_value" key stays the same, instead of having "_createdby_value@OData.Community.Display.V1.FormattedValue" as key.

    The https used is as follows:

    HttpRequestMessage retrieveRequest = new HttpRequestMessage(HttpMethod.Get, the_api_request_url);
    retrieveRequest.Headers.Add("Prefer", "odata.include-annotations=\"*\"");

    HttpMessageHandler messageHandler = new OAuthMessageHandler(serviceUrl, clientId, redirectUrl, new HttpClientHandler());
    HttpClient httpClient = new HttpClient(messageHandler);
    HttpResponseMessage response = httpClient.GetAsync(retrieveRequest.RequestUri.ToString(), HttpCompletionOption.ResponseHeadersRead).Result;
    JObject collection = JsonConvert.DeserializeObject<JObject>(response.Content.ReadAsStringAsync().Result);

     


    I am currently out of clues. Please help.

    Thank you. 

  • Michel van den Brink Profile Picture
    4,697 on at

    (Please ignore this post, I posted a better answer below :-)  )

  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hello again,

    Something that I noticed, you define the local variable 'retrieveRequest' and add the headers to it but, don't actually do anything with that variable, other than reading the URL from it.

    Instead of GetAsync(...) you need SendAsync(...) to send your whole request. 

      

    Try this line:

    HttpResponseMessage response = httpClient.SendAsync(retrieveRequest, HttpCompletionOption.ResponseHeadersRead).Result;

      

    An updated version of your posted example would be:

    HttpRequestMessage retrieveRequest = new HttpRequestMessage(HttpMethod.Get, the_api_request_url);
    retrieveRequest.Headers.Add("Prefer", "odata.include-annotations=\"*\"");
    
    HttpMessageHandler messageHandler = new OAuthMessageHandler(serviceUrl, clientId, redirectUrl, new HttpClientHandler());
    HttpClient httpClient = new HttpClient(messageHandler);
    HttpResponseMessage response = httpClient.SendAsync(retrieveRequest, HttpCompletionOption.ResponseHeadersRead).Result;
    JObject collection = JsonConvert.DeserializeObject<JObject>(response.Content.ReadAsStringAsync().Result);
  • Community Member Profile Picture
    on at

    ヾ(⌐■_■)ノ♪ Works like a charm! Thanks so much again!!

  • Michel van den Brink Profile Picture
    4,697 on at

    Any time! Here to help :-)

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans