在Angular 7中向ASP.NET Core Web API控制器传递参数时,如果参数为空,可能是由于多种原因造成的。以下是一些基础概念、可能的原因、解决方案以及示例代码。
确保ASP.NET Core的路由配置能够匹配Angular发送的请求。
// Startup.cs 或 Program.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
确保控制器方法的参数使用了正确的属性来绑定数据。
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
// ...
}
[HttpPost]
public ActionResult Post([FromBody] MyModel model)
{
// ...
}
}
在Angular中发送请求时,确保设置了正确的Content-Type头。
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
this.http.post('api/my', myModel, httpOptions).subscribe(response => {
// ...
});
如果存在跨域问题,需要在ASP.NET Core中配置CORS策略。
// Startup.cs 或 Program.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAngularApp",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod());
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("AllowAngularApp");
// ...
}
假设我们有一个简单的模型MyModel
和一个控制器MyController
。
MyModel.cs
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
MyController.cs
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpPost]
public ActionResult<MyModel> Post([FromBody] MyModel model)
{
if (model == null)
{
return BadRequest("Model is null");
}
// 处理模型数据
return CreatedAtAction(nameof(Get), new { id = model.Id }, model);
}
[HttpGet("{id}")]
public ActionResult<MyModel> Get(int id)
{
// 根据id获取模型数据
var model = new MyModel { Id = id, Name = "Sample" };
return Ok(model);
}
}
Angular Service
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
private apiUrl = 'api/my';
constructor(private http: HttpClient) {}
postModel(model: any) {
return this.http.post(this.apiUrl, model);
}
getModel(id: number) {
return this.http.get(`${this.apiUrl}/${id}`);
}
}
通过以上步骤和代码示例,你应该能够解决从Angular 7传递参数到ASP.NET Core Web API控制器时参数为空的问题。如果问题仍然存在,请检查网络请求的详细信息,以及是否有任何中间件或过滤器可能影响了请求的处理。
领取专属 10元无门槛券
手把手带您无忧上云