1.Controller action
[HttpPost]
public IActionResult addNewUser(string name)
{
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);
}
I am able to access the same action with Jquery ajax and it is working fine.
$(document).ready(function () {
$.ajax({
method: "POST",
url: "/Home/addNewUser",
data: { 'name': 'cebeDev' }
})
});
Or, Is there anything am missing on the startup.cs file?
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
}
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?}");
});
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
Please help.
What I have tried:
I am working on an angular 2 application using asp.net MVC6. Angular2 Http post method calls the controller action and works properly when there is no parameter/properties, but when i add a parameter to the controller action, The expected JSON mapping is not happening while trying to call action with the parameter values. Debugging the action shows null value to the parameter.