AJAX POST调用MVC接口报405 Method Not Allowed错误求助
解决方案
1. 修复前端AJAX的错误配置
你前端代码里存在两处致命错误:
- 不要同时设置
type: "POST"和dataType: "jsonp":JSONP本质是动态插入script标签实现跨域,只支持GET请求,设置POST完全不生效,相当于实际发了GET请求到你只允许POST的接口,自然返回405。 - 不要在请求头里加
Access-Control-Allow-Origin: '*':这个是服务端返回的响应头,前端请求加这个完全多余,还会触发额外的OPTIONS预检请求,增加出错概率。
修复后的前端代码参考:
$.ajax({ type: "POST", url: "你的实际接口URL", contentType: "application/json; charset=utf-8", // 把参数放到请求体里,和后端接口参数对应 data: JSON.stringify({ key: "你的key值", action: "你的action值" }), dataType: "json", crossDomain: true, success: function (response) { console.log('message: success' + JSON.stringify(response)); }, error: function (error) { console.log('message Error' + JSON.stringify(error)); } });
2. 调整后端接口参数接收规则
你当前的接口参数默认从查询字符串/表单读取,但是前端传的是JSON格式的请求体,路由系统匹配不到对应的接收方法,就会返回405。有两种修复方式:
方式一:用实体类+[FromBody]接收JSON参数
先定义参数实体类:
public class MethodTestRequest { public string Key { get; set; } public string Action { get; set; } }
修改接口方法:
[System.Web.Http.HttpPost] public IHttpActionResult MethodTest([FromBody] MethodTestRequest request) { string key = request.Key; string action = request.Action; // 原有逻辑 }
方式二:前端改成表单格式传参(不需要改后端代码)
把前端的contentType改成application/x-www-form-urlencoded,data不用JSON序列化:
$.ajax({ type: "POST", url: "你的实际接口URL", contentType: "application/x-www-form-urlencoded; charset=utf-8", data: { key: "你的key值", action: "你的action值" }, dataType: "json", crossDomain: true, // 其他回调逻辑不变 });
3. 处理OPTIONS预检请求
浏览器跨域发送非简单请求(比如contentType是application/json)时会先发送OPTIONS预检请求,你的服务端如果没有处理OPTIONS请求,IIS会直接返回405。可以在web.config里加配置放行OPTIONS请求:
<system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> <modules runAllManagedModulesForAllRequests="true"> <remove name="WebDAVModule" /> </modules> <!-- 原有httpProtocol配置保留即可 --> </system.webServer>
也可以在Global.asax里添加代码直接处理OPTIONS请求:
protected void Application_BeginRequest() { if (Request.HttpMethod == "OPTIONS") { Response.StatusCode = (int)System.Net.HttpStatusCode.OK; Response.End(); } }
内容的提问来源于stack exchange,提问作者Jefferson
相关产品推荐
相关产品推荐

