Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 299 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

#1
I want to send dynamic object like

new { x = 1, y = 2 };

as body of HTTP POST message. So I try to write

var client = new HttpClient();

but I can't find method

client.PostAsJsonAsync()

So I tried to add Microsoft.AspNetCore.Http.Extensions package to project.json and add

using Microsoft.AspNetCore.Http.Extensions;

to uses clause. However It didn't help me.

So what is the easiest way to send POST request with JSON body in ASP.NET Core?

Reply

#2
I would add to the accepted answer that you would also want to add the `Accept` header to the `httpClient`:

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Reply

#3
I use this class:

public class JsonContent : StringContent
{
public JsonContent(object obj) :
base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
{ }
}

Sample of usage:

new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
Reply

#4
You should add reference to "Microsoft.AspNet.WebApi.Client" package (read [this article][1] for samples).

Without any additional extension, you may use standard `PostAsync` method:

client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));

where `jsonInString` value you can get by calling `JsonConvert.SerializeObject(<your object>);`


[1]:

[To see links please register here]

Reply

#5
You are right that this has long since been implemented in .NET Core.

At the time of writing (September 2019), the `project.json` file of NuGet 3.x+ has been superseded by `PackageReference` (as explained at

[To see links please register here]

).

To get access to the `*Async` methods of the `HttpClient` class, your `.csproj` file must be correctly configured.

Open your `.csproj` file in a plain text editor, and make sure the first line is
`<Project Sdk="Microsoft.NET.Sdk.Web">`
(as pointed out at

[To see links please register here]

).

To get access to the `*Async` methods of the `HttpClient` class, you also need to have the correct **package reference** in your `.csproj` file, like so:

<ItemGroup>
<!-- ... -->
<PackageReference Include="Microsoft.AspNetCore.App" />
<!-- ... -->
</ItemGroup>

(See

[To see links please register here]

.
Also: *We recommend applications targeting ASP.NET Core 2.1 and later use the Microsoft.AspNetCore.App metapackage*,

[To see links please register here]

)

Methods such as `PostAsJsonAsync`, `ReadAsAsync`, `PutAsJsonAsync` and `DeleteAsync` should now work out of the box. (No using directive needed.)

**Update:** The PackageReference tag is no longer needed in .NET Core 3.0.
Reply

#6
Microsoft now recommends using an `IHttpClientFactory` with the following benefits:

- Provides a central location for naming and configuring logical
`HttpClient` instances. For example, a client named github could be
registered and configured to access GitHub. A default client can be
registered for general access.
- Codifies the concept of outgoing middleware via delegating handlers
in `HttpClient`. Provides extensions for Polly-based middleware to take
advantage of delegating handlers in `HttpClient`.
- Manages the pooling and lifetime of underlying
`HttpClientMessageHandler` instances. Automatic management avoids
common DNS (Domain Name System) problems that occur when manually
managing `HttpClient` lifetimes.
- Adds a configurable logging experience (via `ILogger`) for all requests
sent through clients created by the factory.

[To see links please register here]


Setup:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
// Remaining code deleted for brevity.

POST example:

public class BasicUsageModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;

public BasicUsageModel(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}

public async Task CreateItemAsync(TodoItem todoItem)
{
var todoItemJson = new StringContent(
JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
Encoding.UTF8,
"application/json");

var httpClient = _clientFactory.CreateClient();

using var httpResponse =
await httpClient.PostAsync("/api/TodoItems", todoItemJson);

httpResponse.EnsureSuccessStatusCode();
}

[To see links please register here]


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through