首页 > 解决方案 > 带有asp.net webapi的角度2中put方法的Http失败响应

问题描述

当我尝试在我的 angular 2 应用程序的 userdetails 页面上更新我的 userdetails 时,我正面临 put 方法的“Http 失败响应”。任何人都可以为我提供解决以下错误的想法。

错误:- 消息:“请求的资源不支持 http 方法 'PUT'。” 消息:“ http://localhost/TestWebAPI/api/UserDetails的 Http 失败响应:405 Method Not Allowed”

userdetails.component.ts

onUpdateUserClick(index)
{   
    this.objuserservice.UpdateUser(this.UpdateUser).subscribe
    (
        (response) => {
            this.UpdateUser = response;
            this.userslist[this.updateIndex].email = this.UpdateUser.email;
            this.userslist[this.updateIndex].personname = this.UpdateUser.personname;
            this.userslist[this.updateIndex].mobile = this.UpdateUser.mobile;
            this.userslist[this.updateIndex].dateofbirth = this.UpdateUser.dateofbirth;
            this.userslist[this.updateIndex].monthofbirth = this.UpdateUser.monthofbirth;this.userslist[this.updateIndex].yearofbirth=this.UpdateUser.yearofbirth;
            this.userslist[this.updateIndex].gender = this.UpdateUser.gender;
            this.userslist[this.updateIndex].country = this.UpdateUser.country;
        },
        (error)=>{ 
        });  
}

users.service.ts

UpdateUser(userobj:User):Observable<User>
{
    return this.http.put<User>(`/TestWebAPI/api/UserDetails`,userobj,responseType:"json"});              
}

这是我的 asp.netwebapi(TestWebAPI) 项目代码,

public void Put(int id, [FromBody]user objuser)
{
    dbentity.Entry(objuser).State = System.Data.Entity.EntityState.Modified;
    dbentity.SaveChanges();
}

标签: angularasp.net-web-api

解决方案


如果你在 Web API 中有默认路由,你应该id在 Angular 的 URL 中传递它,比如:

UpdateUser(userobj:User):Observable<User>
{  
    this.http.put<User>("/TestWebAPI/api/UserDetails/" + userObj.Id, userobj,
        responseType:"json"});
}

推荐阅读