Angular2 http post没有将json对象传递给MVC 6控制器动作

时间:2016-03-14 22:48:34

标签: http-post angular asp.net-core-mvc

我正在使用asp.net MVC6处理角度2应用程序。 Angular2 Http post方法调用控制器操作并且在没有参数/属性时正常工作,但是当我向控制器操作添加参数时,尝试使用参数值调用操作时不会发生预期的JSON映射。调试操作会显示参数的空值。 我测试了this discussion中提供的所有解决方案,但我仍然得到参数的空值。

debug screenshot

这是我的代码

  

1.控制器动作

[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);
    }

请帮忙。

修改

Please find the request details from dev tools

1 个答案:

答案 0 :(得分:0)

我从这个discussion得到了一个解决方案,现在我可以使用angular2 Http请求方法而不是post来发布Json数据。控制器操作在调试时显示对象值。我已经使用不同类型的对象和对象列表进行了测试,一切正常。

感谢@Pardeep Jain提供示例代码。

<强> BaseService.ts

protected ExecutePost(action: string, data: any) {
        let _body = JSON.stringify(data);
        let headers = new Headers({ 'Content-Type': 'application/json;charset=utf-8' });

        let requestoptions: RequestOptions = new RequestOptions({
            method: RequestMethod.Post,
            url: this._baseUrl + action,
            headers: headers,
            body: _body
        })

        return this.http.request(new Request(requestoptions))
            .map((res: Response) => { return res.json(); });
    }