使用在localhost上运行的启用CORS的ASP.NET Web API 2,我可以执行GET和POST请求,但不能执行PUT和DELETE请求

时间:2014-06-03 04:20:28

标签: jquery ajax asp.net-web-api cors

enter image description here

红色的“NetworkError:...”消息来自PUT和DELETE请求。任何人都知道为什么会这样吗?我的web.config已经为CORS配置了如下:

<httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
        <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>

My Web API Controller,使用Entity Framework和MSSQL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace CarsoWebApiTraining.Controllers
{
    [EnableCors("*", "*", "*")]
    public class StudentController : ApiController
    {
        GeneralEntities entity = new GeneralEntities();

        StudentController()
        {
            entity.Configuration.LazyLoadingEnabled = false;
        }

        // GET: api/Student
        public IEnumerable<Student> Get()
        {

            return entity.Students;
        }

        // GET: api/Student/5
        public Student Get(int id)
        {
            try
            {
                entity.Students.Where(p => p.StudentID == id).FirstOrDefault();
            }

            catch 
            {
            }

            return entity.Students.Where(p => p.StudentID == id).FirstOrDefault();
        }

        // POST: api/Student
        public void Post([FromBody]Student student)
        {
            entity.Students.Add(student);
            entity.SaveChanges();
        }

        // PUT: api/Student/5
        public void Put(int id, [FromBody]Student student)
        {
            Student selectedStudent = Get(id);
            selectedStudent.Name = student.Name;
            selectedStudent.ICNo = student.ICNo;

            entity.SaveChanges();
        }

        // DELETE: api/Student/5
        public void Delete(int id)
        {
            entity.Students.Remove(Get(id));
            entity.SaveChanges();

        }


    }
}

1 个答案:

答案 0 :(得分:0)

这是我发现的。这link可能会帮助您找到原因。您可以在托管环境中检查是否允许使用这些动词。

The other common problem when using the CORS support from 
Thnktecture.IdentityModel is that the handler for .NET code (the ExtensionlessUrlHandler) 
by default only allows GET, POST, HEAD and DEBUG methods.