question

wavemaster avatar image
0 Votes"
wavemaster asked StevenMcKnight-7365 answered

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


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>?

dotnet-aspnet-core-blazordotnet-aspnet-core-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

miwan2-msft avatar image
0 Votes"
miwan2-msft answered miwan2-msft edited

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




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

wavemaster avatar image
0 Votes"
wavemaster answered wavemaster published

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.InvokeNextResultFilterAsync[TFilter,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>gAwaited|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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

miwan2-msft avatar image
0 Votes"
miwan2-msft answered

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.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

wavemaster avatar image
0 Votes"
wavemaster answered

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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

wavemaster avatar image
1 Vote"
wavemaster answered

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!

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

StevenMcKnight-7365 avatar image
0 Votes"
StevenMcKnight-7365 answered

Check your code....


private void AddService()
{Service service = new Service();

Are you in need of a dot at the key\value pair,
{
Service.service = NewService()
}

....and check your formatting...?
Consistency will make your code easier to debug, as well as easier for others to read @MyLadys-4900
Alt/Option + F10 will tab to the formatting toolbar.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.