我有WEBAPI项目和AngularJS客户端项目。 $ http.get调用工作正常,并且带有空数据的$ http.post调用正在工作,但数据的抛出错误为'405(Method Not Allowed)'。我也启用了CORS。请提供解决方案。
我在web.config中添加了以下内容
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS,XYZ" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS,XYZ" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
这是WEBAPI
[HttpPost] public bool SubmitQuesiton(JObject数据) { return Factory.SubmitQuestion(data); }
这是AngularJS代码
data = JSON.stringify(data);
$http({
method: 'POST',
url: "http://localhost:53546/api/demo/SubmitQuesiton",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: data
})
答案 0 :(得分:1)
回答自己的问题。问题是由于CORS,它应该在WEBAPI项目中启用。 CORS启用无法通过WEB.config代码工作,您需要通过后端启用CORS。
注意 - 删除所有web.config CORS启用代码,如果它在web.config中,即下面的代码
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
步骤 1.为WEBAPI项目安装CORS软件包安装包Microsoft.AspNet.WebApi.Cors 2.在WebApiConfig.cs中添加此代码
var corsAttribute = new EnableCorsAttribute("*","Origin, Content-Type, Accept",
"GET, PUT, POST, DELETE, OPTIONS");
config.EnableCors(corsAttribute);
完成。