HTTP Post - how to get the Id from the HTTP Post response and NOT from context.SaveChanges

wavemaster 311 Reputation points
2021-03-02T02:49:27.01+00:00

private void AddService()
{
Service service = new Service();
service.ServiceName = newService.ServiceName;
service.RoleId = 8;
service.IsProcedure = false;
service.ShortForm = newService.ServiceName;
service.Maincat = newService.MainCat;
service.Subcat = null;
service.Strength = null;
service.Package = null;
service.Size = null;
service.Note = null;
string baseUrl = "https://localhost:44384";
var httpClient = _clientFactory.CreateClient("ServerAPI");
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var response = httpClient.PostAsJsonAsync($"{baseUrl}/api/Service/AddNewService", service);

    //need to do stuff here where I need the newly created ServiceId

}

How do I get the Id of the newly inserted record from <response>?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,618 questions
Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,595 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Wang-MSFT 1,061 Reputation points
    2021-03-02T07:16:33.53+00:00

    Hi, @MyLadys-4900,
    You should confirm one things that it will return the newly created Service entity from the HTTP Post response.
    You could get jsonString from response.

        var result = response.Result;  
    

    string jsonString = result.Content.ReadAsStringAsync().Result;
    Then you can deserialize your object from json string:

    Service returnService = JsonSerializer.Deserialize<Service>(jsonString);

    Now, you can get Id from returnService.Id.

    ---
    If the answer doesn’t solve your issue, please provide more details of error that will help us track down what’s happening.
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Michael Wang

    1 person found this answer helpful.
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. wavemaster 311 Reputation points
    2021-03-05T15:25:54.6+00:00

    There was indeed something wrong with what I did. Got that fixed.

    This is what I ended up with:

        var response = await httpClient.PostAsync($"{baseUrl}/api/Service/AddNewService", content);
        var data = await response.Content.ReadAsStringAsync();
        Service result = new Service();
    
        if (response.IsSuccessStatusCode)
        {
            result = JsonSerializer.Deserialize<Service>(data);    
        }
        else 
        {
            errorMessage = data;
        }
    
        if (result != null) { // do stuff }
    

    This all works, thanks miwan2!

    1 person found this answer helpful.
    0 comments No comments

  2. wavemaster 311 Reputation points
    2021-03-02T16:22:38.207+00:00

    I am getting an exception on string jsonString;

    jsonString
    "System.InvalidOperationException: No route matches the supplied values.\r\n at Microsoft.AspNetCore.Mvc.CreatedAtRouteResult.OnFormatting(ActionContext context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsyncCore(ActionContext context, ObjectResult result, Type objectType, Object value)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor.ExecuteAsync(ActionContext context, ObjectResult result)\r\n at Microsoft.AspNetCore.Mvc.ObjectResult.ExecuteResultAsync(ActionContext context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultAsync(IActionResult result)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResultFilterAsyncTFilter,TFilterAsync\r\n--- End of stack trace from previous location ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructu
    re.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()\r\n--- End of stack trace from previous location ---\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.In
    voke(HttpContext httpContext)\r\n at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\r\n at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)\r\n\r\nHEADERS\r\n=======\r\nAccept: application/json\r\nContent-Type: application/json; charset=utf-8\r\nHost: localhost:44384\r\nTransfer-Encoding: chunked\r\ntraceparent: 00-43717d7039b2dc408b1f43ba3f8a5584-d0b9cf536afffd46-00\r\n"

    result from the immediate window:
    result
    {StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
    {
    Server: Microsoft-IIS/10.0
    X-Powered-By: ASP.NET
    Date: Tue, 02 Mar 2021 16:19:09 GMT
    Content-Type: text/plain
    Content-Length: 2483
    }}
    Content: {System.Net.Http.HttpConnectionResponseContent}
    Headers: {Server: Microsoft-IIS/10.0
    X-Powered-By: ASP.NET
    Date: Tue, 02 Mar 2021 16:19:09 GMT
    }
    IsSuccessStatusCode: false
    ReasonPhrase: "Internal Server Error"
    RequestMessage: {Method: POST, RequestUri: 'https://localhost:44384/api/Service/AddNewService', Version: 1.1, Content: System.Net.Http.Json.JsonContent, Headers:
    {
    Accept: application/json
    traceparent: 00-2e529e5c626bc3438cd69aecec935503-aa1da66de6f9b14a-00
    Transfer-Encoding: chunked
    Content-Type: application/json; charset=utf-8
    }}
    StatusCode: InternalServerError
    TrailingHeaders: {}
    Version: {1.1}

    and response:
    response
    Id = 3897, Status = RanToCompletion, Method = "{null}", Result = "StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:\r\n{\r\n Server: Microsoft-IIS/10.0\r\n X-Powered-By: ASP.NET\r\n Date: Tue, 02 Mar 2021 16:19:09 GMT\r\n Content-Type: text/plain\r\n Content-Length: 2483\r\n}, Trailing Headers:\r\n{\r\n}"
    AsyncState: null
    CancellationPending: false
    CreationOptions: None
    Exception: null
    Id: 3897
    Result: {StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
    {
    Server: Microsoft-IIS/10.0
    X-Powered-By: ASP.NET
    Date: Tue, 02 Mar 2021 16:19:09 GMT
    Content-Type: text/plain
    Content-Length: 2483
    }, Trailing Headers:
    {
    }}
    Status: RanToCompletion

    It did indeed as there is a Service record in the db

    0 comments No comments

  3. Michael Wang-MSFT 1,061 Reputation points
    2021-03-03T07:19:43.817+00:00

    System.InvalidOperationException: No route matches the supplied values

    It said the url {baseUrl}/api/Service/AddNewService", service); you post doesn't exist. Please check the route firstly.

    0 comments No comments

  4. wavemaster 311 Reputation points
    2021-03-03T14:33:15.167+00:00

    This targets NET5 so I have Swagger to look at to see what it thinks is the route:
    /api/Service/AddNewService

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.