PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 19, 2022

[FIXED] Why does this string not get bound to a filename parameter in ASP.NET .Core API Action?

 May 19, 2022     asp.net-core, asp.net-core-webapi, c#, parameterbinding     No comments   

Issue

I'm testing an API with fiddler using the following header and body and POSTing at http://localhost:50063/api/image:

User-Agent: Fiddler
Content-Type: application/json; charset=utf-8
Host: localhost:50063
Content-Length: 32330

{"filename": "bot.png", "file": "base64 image ellided for brevity"}

Example code from tutorial

[ApiController]
[Produces("application/json")]
[Route("api/Image")]
public class ImageController : Controller
{

    // POST: api/image
    [HttpPost]
    public void Post(byte[] file, string filename)
    {
        string filePath = Path.Combine(_env.ContentRootPath, "wwwroot/images/upload", filename);
        if (System.IO.File.Exists(filePath)) return;
        System.IO.File.WriteAllBytes(filePath, file);
    }

    //...

}

First I got error 500 with the filename being null. I added [ApiController] Attribute to the controller class and I get error 400 filename invalid.

When I make the same request here the filename binds to the complex class:

    [HttpPost("Profile")]
    public void SaveProfile(ProfileViewModel model)
    {
        string filePath = Path.Combine(_env.ContentRootPath, "wwwroot/images/upload", model.FileName);
        if (System.IO.File.Exists(model.FileName)) return;
        System.IO.File.WriteAllBytes(filePath, model.File);
    }

    public class ProfileViewModel
    {
        public byte[] File { get; set; }
        public string FileName { get; set; }
    }

Why is that happening?


Solution

Request content can only be read from the body once.

In first example, after populating array it can populate string as body has already been read.

In second example it populates the model in one read of the body.

Once the request stream is read for a parameter, it's generally not possible to read the request stream again for binding other parameters.

Reference Model Binding in ASP.NET Core



Answered By - Nkosi
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing