我正在使用asp.net MVC6的角度2應用程序。 Angular2 Http post方法調用控制器動作並在沒有參數/屬性時正常工作,但是當我向控制器動作添加參數時,嘗試使用參數值調用動作時不會發生預期的JSON映射。調試該操作會向參數顯示空值。 我使用this discussion中提供的所有解決方案進行了測試,但仍得到參數的空值。Angular2 http post沒有將json對象傳遞給MVC 6控制器動作
這裏是我的代碼
1.Controller行動
[HttpPost]
public IActionResult addNewUser(string name) //tested with [FromBody]
{
return Json(name);
}
2.angular2 HTTP POST
--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);
}
請幫助。
EDIT
Please find the request details from dev tools
你能提供是從開發工具的網絡標籤在你的瀏覽器發送的HTTP請求的內容?你的Angular2看起來很好。唯一可能的是你忘了導入'Headers'類... –
hi @ThierryTemplier,我已經更新了請求的詳細信息,請看看。 –