網上看到很多關於這這個問題的解決方案,但是都不正確,
我也恰巧遇到這個問題,所有把正確的解決方案寫出來,
希望給后來人參考,如有不同意見歡迎指正
namespace WebApi.Controllers
{
[Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public IActionResult Post([FromBody] string value) { return Ok(value); } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } } }
### POST http://localhost:49518/api/values HTTP/1.1 Content-Type: application/json "ddddff"
var value = '1111';
$.ajax({ type: 'POST', contentType: "application/json", url: url, data: value, //如果是 string,int 直接傳值 ,如果是模型 就要傳對象{} .......省略 });
也就是data 不要傳{} 對象,直接傳字符串或者int