question

osyris-3187 avatar image
0 Votes"
osyris-3187 asked DuaneArnold-0443 answered

Api Post Requist with single Paramater

This would probably be a very easy problem to solve but i dont seem to udnerstand it.

Client-side:
axios.post("https://localhost:44332/api/Products/CreateCategory",name)

backend:

 [HttpPost("CreateCategory")]
         public async Task<IActionResult> CreateCategory(String name)
         {


if try that or this:

 [HttpPost("CreateCategory")]
         public async Task<IActionResult> CreateCategory([FromBody] string name)
         {


it does not work but if i do this:

 [HttpPost("CreateCategory")]
         public async Task<IActionResult> CreateCategory(CategoryDto dto)
         {

model:

     public class CategoryDto
     {
         public string Name { get; set; }
     }

it works perfectly

How can use post request without the use of models.

dotnet-aspnet-generaldotnet-aspnet-core-mvcdotnet-aspnet-core-webapi
· 2
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.

HTML forms submit name value pairs. Your client code is missing the "Name" property and only submits the value. The model works because you included the name. If you take a look at the Network trace in the browser's dev tools you can see the submitted values which should help with your understanding. Anyway, if you are submitting an applicatoin/json content-type then the name variable should have the following format.

 {"Name": "value"}

the "Name" property must match the "Name" action input. Keep in mind, your question is related to fundamental model binding and general HTML forms.


0 Votes 0 ·

Thank you for your reply if i have tried what you said:

Client- side:

   const res = await axios.post("https://localhost:44332/api/Products/CreateCategory",{"Name": "test"})

back-end:

 [HttpPost("CreateCategory")]
             public async Task<IActionResult> CreateCategory([FromBody]string Name)
             {
                 if (!string.IsNullOrEmpty(Name))
                 {
                     var find = await _dbContext.categories.FirstOrDefaultAsync(x => x.Name == Name);
        
                     if (find != null)
                         return BadRequest("Category name is already used");
        
                     var newcat = new Category()
                     {
                         Name = Name,
                         amount = 0
                     };
        
                     _dbContext.categories.Add(newcat);
                     await _dbContext.SaveChangesAsync();
        
                     return Ok();
                 }
                 return BadRequest("Name is not filled in");
             }

It still gives me a error 400

I also tried without the [FromBody] and it did not work as well.
the axios url path is also 100% good


0 Votes 0 ·
ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered

Hi @osyris-3187,

To send a request with single parameter, you could try to use the following method:

1. Send parameter via query string.

Append the parameter at the end of the request url, code as below:

         //send parameter via query string
         var name = "Tom";
         var res = axios.post("https://localhost:44310/api/ToDo/CreateCategory?name=" + name);

Api Controller:

     [Route("api/[controller]")]
     [ApiController]
     public class TodoController : ControllerBase
     { 
         [HttpPost("CreateCategory")]
         public async Task<IActionResult> CreateCategory(string name)
         {
             return Ok("Success");
         }

The result as below:

125304-3.gif

2. Send parameter via Form

Code like this:

         const resp = axios.post('https://localhost:44310/api/ToDo/CreateCategory', 'name=world');  

Api Controller:

     [Route("api/[controller]")]
     [ApiController]
     public class TodoController : ControllerBase
     { 
         [HttpPost("CreateCategory")]
         public async Task<IActionResult> CreateCategory([FromForm]string name)
         {
             return Ok("Success");
         }

The result like this:

125294-5.gif


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,
Dillion






3.gif (186.7 KiB)
5.gif (233.1 KiB)
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.

DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered

You need to understand Encapsulation and information hiding.

https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)

That's what a DTO, a class, provides is encapsulation. The 'name' data can have data that can make the URL malformed when passing data. The DTO prevents the URL from becoming malformed.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

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.