简体   繁体   中英

How to send a POST request with JSON in body from python to asp.net?

I want make a POST request from a python scrypt to asp.net api.

requests.post(apiUrl, data={'key': 'value'})

This is just a simple request for testing purpose

My action from api controller

    [HttpPost]
    [Route("/api/test")]
    public  ActionResult PostAsync(object entity)
    {
        return Ok();
    }

again..just for test. To receive the request I should add the

            services.Configure<ApiBehaviorOptions>(options =>
        {
             options.SuppressInferBindingSourcesForParameters = true;
        });

in Startup.cs With all of that, my action is hit by the entity is just an empty object.

Try using the json= instead of data= argument to post .

Python:

import requests

reqUri = 'http://localhost:51415/weatherforecast'
result = requests.post(reqUri, json={'key':'value'})
print(result)

ASP Net Core Controller:

namespace NetCoreTestAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [AllowAnonymous]
        [HttpPost]
        public IActionResult Create(object msgBody)
        {
            Console.WriteLine(msgBody.ToString());
            WeatherForecast retval = new WeatherForecast();
            return new OkObjectResult(retval);
        }
    }
}

Result @ Server:

Route matched with {action = "Create", controller = "WeatherForecast"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Create(System.Object) on controller NetCoreTestAPI.Controllers.WeatherForecastController (NetCoreTestAPI).
{"key": "value"}

Result @ Python Client:

<Response [200]>

EDIT: Another option if you want to continue to use the data= parameter is to mark your ASP.NET Controller Action with the [FromForm] attribute. From the docs on requests :

Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made

For this to work, you'll need to create a receiving class in ASP.NET for the Controller to deserialize into. This works fine:

public class TestObject
{
    public string key { get; set; }
}

[AllowAnonymous]
[HttpPost]
public IActionResult Create([FromForm] TestObject msgBody)
{
    Console.WriteLine(msgBody.ToString());
    WeatherForecast retval = new WeatherForecast();
    return new OkObjectResult(retval);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM