错误的请求:对ASP.Net CORE Web API的角度服务调用



我有一个角度服务,它在表单提交时被调用。然而,当我试图传递一个复杂的对象public NewDogCreation(dog: Dog)时,它会返回一个400错误的请求。如果我更改方法的签名以返回一个简单的字符串或intpublic NewDogCreation(Id: any),那么服务调用就会毫无问题地命中web api方法,并在visual studio中的断点处停止。Postman在将一个简单属性传递给web api控制器时,也成功地运行了api请求。

以下是我的全部代码:

角度服务

//Create New Dog Method
public NewDogCreation(dog: Dog): Observable<Dog> {
console.log('service data = '+ JSON.stringify(dog));
let apiRoute = this.url + '/' + 'AddNewCanine';
let attempts: any;
return this.http.post<Dog>(apiRoute, dog)
.pipe(
map((dog: Dog) => { return dog; }));    
} //end of NewDogCreation

.Net Core Web API控制器操作

//Add Individual Dog
[HttpPost]
[Route("api/CanineManagement/AddNewCanine")]
public IActionResult AddCanine([FromBody] Dog dog)
{
var dogObject = dog;
var response = "Response success"; 
return Ok(response);
}//end of Add Dog API Method

Web API启动中的CORS

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else { }
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
//app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

如有任何建设性意见,我们将不胜感激!

尝试这个

const headers = new HttpHeaders().set('Content-Type','application/json');
return this.http.post<Dog>(apiRoute, JSON.stringify(dog),{headers:headers})
....

相关内容

  • 没有找到相关文章

最新更新