【发布时间】:2016-06-30 04:49:29
【问题描述】:
我正在使用 asp.net MVC6 开发一个 Angular 2 应用程序。 Angular2 Http post 方法调用控制器操作并在没有参数/属性时正常工作,但是当我向控制器操作添加参数时,尝试使用参数值调用操作时未发生预期的 JSON 映射。调试操作会向参数显示空值。 我测试了this discussion 中提供的所有解决方案,但我仍然得到参数的空值。
这是我的代码
1.控制器动作
[HttpPost]
public IActionResult addNewUser(string name) //tested with [FromBody]
{
return Json(name);
}
2.angular2 http 帖子
--UserComponent.ts
this.userService.AddUser(name).subscribe(
res => {
this.toggle('list');
}
);
--UserService.ts
AddUser(name: string) {
return this.ExecutePost('addNewUser', name).map((newUser: string) => { return newUser });
}
--BaseService.ts
protected ExecutePost(action: string, name: string) {
let body = JSON.stringify({ name: name });
let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });
return this.http.post(this._baseUrl + action, body, { headers: headers })
.map(res => { return res.json(); }).catch(this.handleError);
}
我可以使用 Jquery ajax 访问相同的操作,并且工作正常。
$(document).ready(function () {
$.ajax({
method: "POST",
url: "/Home/addNewUser",
data: { 'name': 'cebeDev' }
})
});
或者,startup.cs 文件中是否缺少任何内容?
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseIISPlatformHandler();
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
请帮忙。
编辑
【问题讨论】:
-
您能否提供从浏览器中开发工具的“网络”选项卡发送的 HTTP 请求的内容?你的 Angular2 看起来不错。唯一可能是您忘记导入
Headers类... -
嗨@ThierryTemplier,我已经用请求的详细信息更新了帖子,请看一下。
标签: http-post angular asp.net-core-mvc