Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
1.Controller action
C#
[HttpPost]
public IActionResult addNewUser(string name) //tested with [FromBody]
{
     return Json(name);
}

2.angular2 http post
JavaScript
--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.
JavaScript
$(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
C#
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);
    }

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.
Posted
Updated 1-Sep-16 3:49am
Comments
John C Rayan 15-Mar-16 9:53am    
just pass the parameters without headers, then try with headers

$http.post(url, { name: 'john' })

 
Share this answer
 
Hi,
Did you get solution? if so, please let me know how you did it? I am stuck with the same issue.

Thanks,
SR.
 
Share this answer
 
Comments
Richard Deeming 1-Sep-16 9:37am    
If you want to ask a question, then ask a question[^].

DO NOT post your question as a "solution" to someone else's question!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900