从Angular 2到ASP.net Core的POST请求不起作用.服务器端为空值 [英] POST request from Angular 2 to ASP.net Core doesn't work. Null value on server side
问题描述
后端,ASP.net Core API:
Backend, ASP.net Core API:
[Produces("application/json")]
[Route("api/[controller]")]
public class StoriesController : Controller
{
public static List<Story> STORIES = new List<Story>
{
new Story
{
content = "Some really interesting story about dog",
timeOfAdding = new DateTime(2016, 8, 26),
numberOfViews = 11
},
new Story
{
content = "Even cooler story about clown",
timeOfAdding = new DateTime(2016, 9, 26),
numberOfViews = 11
},
new Story
{
content = "And some not cool story",
timeOfAdding = new DateTime(2016, 10, 26),
numberOfViews = 11
}
};
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
Story story = new Story
{
content = value,
timeOfAdding = DateTime.Now,
numberOfViews = 0
};
STORIES.Add(story);
}
}
TypeScript函数:
TypeScript function:
add(content: string): Observable<Story> {
let body = JSON.stringify({ "value": content });
//let body = { "value": content };
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers});
return this.http.post(this.heroesUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
发送的参数(在Firefox控制台中可见):
Parameters sent (seen in Firefox console):
value = null
怎么了?我已经尝试了在Internet上找到的所有内容:添加/删除标题,删除JSON.stringify,添加/删除[FromBody]
属性.结果每次都是一样的.
What's wrong? I've tried everything that I found in internet: adding/removing headers, removing JSON.stringify, adding/removing [FromBody]
attribute. Result is every time the same.
推荐答案
由于您将值作为JSON传递(如屏幕截图所示),因此应正确使用模型绑定并使用适当的类而不是字符串输入:
Since you're passing your value as JSON (as the screenshot suggests), you should use the model binding correctly and use a proper class instead of a string input:
public class StoryAddRequest
{
public string Value { get; set; }
}
然后您可以在控制器中使用它:
You then can use it in your controller:
// POST api/values
[HttpPost]
public void Post([FromBody] StoryAddRequest request)
{
if (request != null)
{
Story story = new Story
{
content = request.Value,
timeOfAdding = DateTime.Now,
numberOfViews = 0
};
STORIES.Add(story);
}
}
从文档:
请求数据可以采用多种格式,包括JSON,XML和许多其他格式.当您使用
[FromBody]
属性指示您要将参数绑定到请求正文中的数据时,MVC使用一组配置的格式化程序来根据其内容类型来处理请求数据.默认情况下,MVC包含一个用于处理JSON数据的JsonInputFormatter
类,但是您可以添加其他用于处理XML和其他自定义格式的格式化程序.
Request data can come in a variety of formats including JSON, XML and many others. When you use the
[FromBody]
attribute to indicate that you want to bind a parameter to data in the request body, MVC uses a configured set of formatters to handle the request data based on its content type. By default MVC includes aJsonInputFormatter
class for handling JSON data, but you can add additional formatters for handling XML and other custom formats.
这篇关于从Angular 2到ASP.net Core的POST请求不起作用.服务器端为空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!