我很遗憾再次提出类似令人沮丧的问题,但我无法从Angular2配置对Web API 2的http POST请求
fetchBattingAverage() {
let str = JSON.stringify({"foo": "bar"});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
// JSON.stringify({ "abc": "def" })
return this._http.post(
this.baseURL + 'getBatting',
str,
options
)
.map(res => res.json());
}
Web API 2:web config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
Web APi 2.2控制器:
[RoutePrefix("api")]
public class SachinController : ApiController
{
[HttpPost]
[Route("getBatting")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public IHttpActionResult Post([FromBody] string countries)
{
// Do something
return Ok()
}
错误讯息:
OPTIONS http://localhost:54094/api/getBatting 405 (Method Not Allowed)
Response for preflight has invalid HTTP status code 405
请求标题:
OPTIONS /api/getBatting HTTP/1.1
Host: localhost:54094
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
DNT: 1
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8
答案 0 :(得分:0)
显然,Web.Config中还有另一个属性需要删除。
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" /> <!-- Remove this -->
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
</httpProtocol>
</system.webServer>