在ASP.NET Core Web API中出现404错误。使用ASP.NET,我将Angular 7用于前端。当我单击表单的保存按钮时,表单数据以角度到达发布方法,但单击保存后显示404错误。对于此表单,我创建了第一个模型,在其中定义了数据库的属性,然后为该模型创建了控制器,并使用了在模型中声明的属性。
Angular服务ts文件:
export class MurderService {
BaseUrl :string ='';
constructor( private http:HttpClient, private config:ConfigService) {
this.BaseUrl=config.getApiURI();
}
murderQuestionnaire(data: any){
var murderBody={
Dead: data.Dead,
Wounded: data.Wounded,
CriminalsInvolved: data.CriminalsInvolved,
CriminalAppearance: data.CriminalAppearance,
VehiclesUsed: data.VehiclesUsed,
WeaponsDescription :data.WeaponsDescription
};
return this.http.post(this.BaseUrl +'/Complians' , murderBody);//upto here data reaches
successfully
}
}
此服务的API控制器:
[Route("api/[controller]")]
[ApiController]
public class ComplainMurderController : ControllerBase
{
[HttpPost]
[Route("Complians")]
//api:/Complians
public void PostComplainMurder(Complians complian)
{
var complianMurder = new Complians()
{
Dead = complian.Dead,
Wounded = complian.Wounded,
CriminalsInvolved = complian.CriminalsInvolved,
CriminalAppearence = complian.CriminalAppearence,
VehiclesUsed = complian.VehiclesUsed,
WeaponsDescription = complian.WeaponsDescription
};
try
{
// var result = await complian.Add(complianMurder);
AuthenticationContext authenticationContext = new AuthenticationContext();
authenticationContext.Add(complianMurder);
authenticationContext.SaveChanges();
}
catch(Exception ex)
{
throw ex;
}
}
}
}
错误
POST http://localhost:49601/api/Complians 404(未找到)
答案 0 :(得分:1)
您的控制器路由定义为api/[controller]
(在您的情况下,这将导致api/ComplainMurder
)。您的操作定义为Complians
。这些是您的实际路线:api/ComplainMurder/Complians
,与api/Complians
不匹配。
使用此方法更改Angular 7侧面将对其进行修复:
return this.http.post(this.BaseUrl +'/ComplainMurder/Complians' , murderBody);
旁注:小心拼写不正确/不一致(不要抱怨而是拼写),因为将来很可能会引起混乱和/或错误。