在ASP.NET MVC,可以访问表单发布数据:
var thisData = Request.Form["this.data"];
Run Code Online (Sandbox Code Playgroud)
是否可以在Web API ApiController中实现相同的功能?
我正在请求做一个asp.net webapi Post方法,我不能得到一个请求变量.
请求
jQuery.ajax({ url: sURL, type: 'POST', data: {var1:"mytext"}, async: false, dataType: 'json', contentType: 'application/x-www-form-urlencoded; charset=UTF-8' })
.done(function (data) {
...
});
Run Code Online (Sandbox Code Playgroud)
WEB API Fnx
[AcceptVerbs("POST")]
[ActionName("myActionName")]
public void DoSomeStuff([FromBody]dynamic value)
{
//first way
var x = value.var1;
//Second way
var y = Request("var1");
}
Run Code Online (Sandbox Code Playgroud)
我无法以两种方式获取var1内容...(除非我为此创建一个类)
我该怎么做?
我正在尝试将表单序列化值发布到控制器(Web API Self Host).我无法理解为什么NameValueCollection没有正确绑定.客户端使用jQuery:
// Form Submit Handler
$( '#form-parameters' ).submit(function (event) {
event.preventDefault();
var formData = $(this).serialize();
// Post serialized form data
postAssemblyParameters(formData);
});
// Post Form Data to controller test
function postAssemblyParameters(formData){
$.ajax({
url: http://localhost/api/test/1,
type: 'POST',
data: formData,
dataType: 'application/x-www-form-urlencoded',
success: function(x3d) {
},
error: function(xhr) {
}
});
}
Run Code Online (Sandbox Code Playgroud)
服务器端使用Web API Self Host:
public void Post([FromUri] int id, [FromBody] NameValueCollection formData)
{
Console.WriteLine(id); // OK
// Collection is NULL
foreach (var key in formData.AllKeys)
{
foreach …Run Code Online (Sandbox Code Playgroud) 我总是在web api rest post请求到控制器时收到一个空值
在我的控制器中
[HttpPost]
public HttpResponseMessage PostCustomer([FromBody]Customer customer)
{
System.Diagnostics.Debug.WriteLine(customer); #CustomerApp.Models.Customer
System.Diagnostics.Debug.WriteLine(customer.FirstName); #null
}
Run Code Online (Sandbox Code Playgroud)
模型
public class Customer
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
请求:
POST: http://localhost:21894/api/customer/postcustomer
Content-Type: application/json
body: {FirstName: "xxxx", LastName: 'yyyy'}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下解决方案但没有任何效果
任何人都可以通过帮助或正确的链接指导我
答: 提出卷曲请求而不是与邮递员打交道就像这样给了我解决方案
$ curl -H "Content-Type: application/json" -X POST -d '{"FirstName":"Jefferson","LastName":"sampaul"}' http://localhost
:21894/api/customer/postcustomer
Run Code Online (Sandbox Code Playgroud)