AngularJS 1调用ASP.NET Web API出现405(Method Not Allowed)错误求助
分析你的405错误原因及修复方案
嗨,我来帮你拆解这个问题——你遇到的405(Method Not Allowed)错误,核心是前端请求的路由、参数传递方式和后端API的定义不匹配,下面具体说问题和修复步骤:
1. 路由匹配的小问题
你的后端API定义的路由是[Route("api/License/Update")],但Angular的update方法URL末尾多了个斜杠:
update: { method: 'PUT', url: authSettings.apiServiceBaseUri + 'api/License/Update/' }
这个末尾斜杠会让请求变成api/License/Update/?id=xxx,而ASP.NET Web API的路由默认是严格匹配斜杠的,这会导致后端找不到对应的Action,直接返回405。
2. 参数传递方式不对
你的后端Update方法接收的是LicenseViewModel复杂对象,默认情况下Web API会从请求体读取这个参数,但你的前端只把id作为查询参数传了,没有把完整的License数据放在请求体里。而且后端Action也没定义查询参数id,就算路由匹配了,参数也绑定不上。
修复步骤
步骤1:修正Angular $resource的update配置
先去掉URL末尾的斜杠,确保路由和后端完全匹配:
angular.module('portal.core.resources.license') .factory('License', ['$resource', 'authSettings', function ($resource, authSettings) { 'use strict'; var License = $resource( authSettings.apiServiceBaseUri + 'api/License/:id', { id: '@licenseSeq' }, { update: { method: 'PUT', url: authSettings.apiServiceBaseUri + 'api/License/Update' // 去掉末尾斜杠 }, // 其他方法保持不变 licenseTypes: { method: 'GET', url: authSettings.apiServiceBaseUri + 'api/License/types', isArray: true }, licenseStatuses: { method: 'GET', url: authSettings.apiServiceBaseUri + 'api/License/statuses', isArray: true }, funeralServicesAdminFees: { method: 'GET', url: authSettings.apiServiceBaseUri + 'api/License/:id/FuneralServiceAdminFees', isArray: true } } ); return License; }]);
步骤2:正确调用update方法
在控制器里调用update时,要传递完整的License对象(包含licenseSeq和其他属性),这样Angular才会把数据放在请求体里传给后端:
// 假设你已经组装好完整的license对象 var licenseToUpdate = { licenseSeq: 69499, // 这里补上LicenseViewModel的其他属性,比如licenseName、expireDate等 }; License.update(licenseToUpdate).$promise .then(function(response) { console.log("更新成功"); }) .catch(function(error) { console.error("更新失败", error); });
步骤3(可选):用路由参数传id(如果需要)
如果你希望通过路由参数传递id(比如api/License/Update/69499),可以修改后端路由:
[HttpPut] [Authorize] [Route("api/License/Update/{id}")] // 新增id路由参数 public bool Update(int id, LicenseViewModel licenseViewModel) { // 这里可以用id做校验,或者直接从licenseViewModel里取id // 你的业务逻辑... }
对应的Angular update方法也要调整:
update: { method: 'PUT', url: authSettings.apiServiceBaseUri + 'api/License/Update/:id', params: { id: '@licenseSeq' } // 把对象里的licenseSeq绑定到路由参数id }
额外检查点
如果前端和后端是跨域的,别忘了检查ASP.NET Web API的CORS配置是否正确——有时候405错误也会因为CORS没配置好导致。
内容的提问来源于stack exchange,提问作者Simon Diplomat
相关产品推荐
相关产品推荐

