ASP.NET Core API模型绑定和Action数据返回格式
参考文档:https://www.cnblogs.com/FlyLolo/p/ASPNETCore2_20.html
模型绑定
- [FromQuery] - 从URL中取值。
- [FromRoute] - 从路由中取值。
- [FromForm] - 从表单中取值。Postman使用
form-data
或x-www-form-urlencoded
调用。Content-Type
对应multipart/form-data
或application/x-www-form-urlencoded
- [FromBody] - 从HTTP Body取值,通常用于取实体类的JSON, XML。Postman使用
raw
调用。Content-Type
对应application/json
- [FromHeader] - 从请求头中取值。
- [FromServices]- 从DI容器取值,获取服务。DI预设是使用Constructor Injection
multipart/form-data与x-www-form-urlencoded区别
- multipart/form-data:既可以上传文件等二进制数据,也可以上传表单键值对,只是最后会转化为一条信息。
- x-www-form-urlencoded:只能上传键值对,并且键值对都是间隔分开的。
raw
- 可以上传任意格式的文本,可以上传text、json、xml、html等
binary
- 相当于Content-Type:application/octet-stream,从字面意思得知,只可以上传二进制数据,通常用来上传文件,由于没有键值,所以,一次只能上传一个文件。
using Microsoft.AspNetCore.Mvc;
using System;
using WebApplication1.Filter;
namespace WebApplication1.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public void Get()
{
}
[HttpGet("FirstSample/{id}")]
public IActionResult FirstSample(
[FromHeader] string header,
[FromForm] string form,
[FromRoute] string id,
[FromQuery] string query)
{
return Ok($"header: {header}, form: {form}, id: {id}, query: {query}");
}
public IActionResult DISample([FromServices] ILogger<WeatherForecastController> logger)
{
return Content($"logger is null: {logger == null}.");
}
public IActionResult BodySample([FromBody] Test model)
{
return Ok(model);
}
[WebApiAttribute]
[HttpPost("Post")]
public Test Post([FromBody] Test test)
{
return test;
}
[WebApiAttribute]
[HttpPost("UploadFile")]
public void PostList([FromForm] string person, [FromForm] IFormCollection formCollection)
{
var file = formCollection.Files.GetFile("filename");
using var ms = new MemoryStream();
file.CopyTo(ms);
var fileBytes = ms.ToArray();
//var fileStream = file.OpenReadStream();
//using var bytes = new byte[file.Length];
//fileStream.Read(bytes, 0, (int)file.Length);
Console.WriteLine(person);
}
}
public class Test {
public string Name { get; set; }
public string Summary { get; set; }
}
}
Action数据返回格式
using System.Threading.Tasks;
using System.Net.Http.Json;
using System.IO;
using System;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication3.Controllers
{
[ApiController]
[Route("[controller]")]
public class HomeController : Controller
{
public IActionResult Index() => Redirect("/swagger");
[HttpGet("ObjStr")]
public IActionResult Obj() => Ok(123546);
//返回任意值
public async Task<ActionResult> OkObj() => Ok(await Task.FromResult(1));
//返回文本
public ActionResult ContentResultDemo() => Content(Guid.NewGuid().ToString());
//返回一个空对象
public ActionResult EmptyResultDemo() => new EmptyResult();
/// <summary>
/// FileContentResult的用法(返回图片)
/// </summary>
/// <returns>显示一个文件内容</returns>
public ActionResult FileContentResultDemo()
{
FileStream fs = new FileStream(Path.Combine(@"/Images/001.jpg"), FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[Convert.ToInt32(fs.Length)];
fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
string contentType = "image/jpeg";
return File(buffer, contentType);
}
//返回一个文件对象
public ActionResult FilePathResult() => File(Path.Combine(@"/Images/123.jpg"), "image/jpeg");
//HttpUnauthorizedResult 的用法(抛出401错误)
public ActionResult HttpUnauthorizedResult() => Unauthorized();
//HttpStatusCodeResult的方法(返回错误状态信息)
public ActionResult HttpStatusCodeResultDemo() => StatusCode(500, "System Error");
// HttpNotFoundResult的使用方法
public ActionResult HttpNotFoundResultDemo() => NotFound("not found action");
//返回一个json对象
public ActionResult JsonResultDemo() => Json(new { name = "json" });
//RedirectResult的用法(跳转url地址)
public ActionResult RedirectResultDemo() => Redirect("https://www.baidu.com/");
//RedirectToRouteResult的用法(跳转的action名称)
public ActionResult RedirectToRouteResultDemo() => RedirectToAction(@"FileContentResultDemo");
// ViewResult的用法(返回视图)
public ActionResult ViewResultDemo() => View();
//PartialViewResult的用法(返回部分视图)
public PartialViewResult PartialViewResultDemo() => PartialView();
}
}