Angular2 HTTP POST没有通过JSON对象MVC 6控制器动作 [英] Angular2 http post not passing the json object to MVC 6 controller action

查看:1176
本文介绍了Angular2 HTTP POST没有通过JSON对象MVC 6控制器动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net MVC6角2应用程序。 Angular2 HTTP POST方法调用控制器动作和正常工作时,有没有参数/性能,但是当我一个参数添加到控制器的动作,同时试图调用的参数值行动的预期JSON映射没有发生。调试行动表明空值的参数。
我在<一所提供的所有解决方案测试href=\"https://stackoverflow.com/questions/35432527/angular2-http-post-request-not-binding-to-asp-net-5-controllers-action#comment58564010_35432972\">this讨论,但还是我得到空值的参数。

调试截图

这是我的code


  

1.Controller行动


  [HttpPost]
公共IActionResult AddNewUser函数(字符串名称)//与测试[FromBody]
{
     返回JSON(名);
}


  

2.angular2 HTTP POST


   -  UserComponent.ts
this.userService.AddUser(名称).subscribe(
            RES =&GT; {
                this.toggle(名单');
            }
        );--UserService.ts
ADDUSER(名称:字符串){
        返回this.ExecutePost('AddNewUser函数',名称).MAP((NEWUSER:字符串)=&GT; {返回NEWUSER});
    }--BaseService.ts
保护ExecutePost(动作:字符串名称:字符串){
        让身体= JSON.stringify({名:名});
        让标题=新的报头({'的Content-Type:应用/ JSON的;字符集= utf-8'});        返回this.http.post(this._baseUrl +动作,身体,{标题:标题})
            .MAP(RES =&GT; {返回res.json();})赶上(this.handleError)。
    }

我能够访问与jQuery的阿贾克斯一样的动作,这是工作的罚款。

  $(文件)。就绪(函数(){
        $阿贾克斯({
            方法:POST,
            网址:/首页/ AddNewUser函数
            数据:{'名':'cebeDev'}
        })    });

或者,有什么我缺少的startup.cs文件?


  

Startup.cs


 公共类启动
    {
        公共启动(IHostingEnvironment ENV)
        {
            //设置配置源。
            VAR建设者=新ConfigurationBuilder()
                .AddJsonFile(appsettings.json)
                .AddJsonFile($。AppSettings的{} env.EnvironmentName以.json,可选:真)
                .AddEnvironmentVariables();            如果(env.IsDevelopment())
            {
                //这将推动通过应用洞察管道遥测数据的速度更快,让你立即看到结果。
                builder.AddApplicationInsightsSettings(developerMode:真);
            }
            配置= builder.Build();
        }        公共IConfigurationRoot配置{搞定;组; }        //此方法被运行时调用。使用此方法可以服务于容器中添加。
        公共无效ConfigureServices(IServiceCollection服务)
        {
            //添加架构服务。
            services.AddApplicationInsightsTelemetry(结构);            services.AddMvc();
        }        //此方法被运行时调用。使用此方法来配置HTTP请求管道。
        公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment ENV,ILoggerFactory的LoggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection(记录));
            loggerFactory.AddDebug();            app.UseApplicationInsightsRequestTelemetry();            如果(env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            其他
            {
                app.UseExceptionHandler(/首页/错误);
            }            app.UseIISPlatformHandler();            app.UseApplicationInsightsExceptionTelemetry();            app.UseStaticFiles();            app.UseMvc(路线=&GT;
            {
                routes.MapRoute(
                    名称:默认,
                    模板:{控制器= HOME} / {行动=指数} / {?ID});
            });
        }        //入口点的应用程序。
        公共静态无效的主要(字串[] args)=&GT; WebApplication.Run&LT;&启动GT;(参数);
    }

请帮忙。

修改

请找到开发工具的要求细节


解决方案

我从这个讨论的解决方案,现在我能够使用后angular2 HTTP请求方法,而不是post.The控制器动作显示了对象的值,而调试JSON数据。我曾与不同类型的对象和对象名单,测试,一切工作正常。

感谢@Pardeep耆那教为您的样品code。

BaseService.ts

 保护ExecutePost(动作:字符串数据:任意){
        让_body = JSON.stringify(数据);
        让标题=新的报头({'的Content-Type:应用/ JSON的;字符集= utf-8'});        让requestoptions:RequestOptions =新RequestOptions({
            方法:RequestMethod.Post,
            网址:this._baseUrl +动作,
            标题:标题,
            身体:_body
        })        返回this.http.request(新请求(requestoptions))
            .MAP((RES:响应)=&GT; {返回res.json();});
    }

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. I tested with all the solutions provided in this discussion , but still i am getting the null value for the parameter.

debug screenshot

Here is my code

1.Controller action

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

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)
        {
            // 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.

EDIT

Please find the request details from dev tools

解决方案

I got a solution from this discussion and now I am able to post the Json data using angular2 Http request method instead of post.The controller action shows the object values while debugging. I have tested with the different types of objects and list of objects and everything is working fine.

Thanks @Pardeep Jain for your sample code.

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

这篇关于Angular2 HTTP POST没有通过JSON对象MVC 6控制器动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆