问题
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
回答1:
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(); });
}
来源:https://stackoverflow.com/questions/35999561/angular2-http-post-not-passing-the-json-object-to-mvc-6-controller-action