Can any one point me in the right direction, which is the best way to pass in asp.net core multiple parameters to a webapi controller where one of them is an image?
I know that in MVC you can do something like this
public ActionResult Index(IEnumerable<HttpPostedFileBase> files, FormCollection form)
{
}
instead of an IEnumerable
and the FormCollection
I would like to do something like this
public ActionResult Index(byte[] file, string name, DateTime createdDate )
You can't post a byte[]
. The ASP.NET Core equivalent of HttpPostedFileBase
is IFormFile
.
You shouldn't use FormCollection
. Instead, create a view model that you can bind to, which houses all the properties you're posting. You can also include your file upload property within this view model as well. For example:
public class MyViewModel
{
public IFormFile File { get; set; }
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
}
Then:
public IActionResult Index(MyViewModel model)
ASP.NET Core doesn't support posting via multiple different ways (HTML form, JSON, etc.) on the same action. You don't need to do anything special for a regular old HTML form post, but for posting something like JSON, you'd have to decorate your action param with [FromBody]
:
public IActionResult Index([FromBody]MyViewModel model)
Posting with Postman, you can post as x-www-form-urlencoded
or multipart/form-data
(the same as a normal form post), but if you need to post JSON from there and accept a post from an HTML form, you'll need two separate actions: one with the [FromBody]
attribute and one without. You can largely factor out the contents of the action into a common method both can use to prevent code duplication:
[HttpPost("api/index")]
public IActionResult IndexApi([FromBody]MyViewModel model)
=> IndexCore(model);
[HttpPost("index")]
public IActionResult Index(MyViewModel model)
=> IndexCore(model);
protected IActionResult IndexCore(MyViewModel model)
{
// action code here
}
for file you need to use
List<IFormFile> files
other parameters can bu used in the same way.
In ASP.NET Core, you can also use
[FromRoute]
[FromQuery]
[FromBody]
[FromHeader]
[FromForm]
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.