Web api使CORS无法正常工作

我无法使用ajax访问asp.net-web-api中的资源。 我为所有请求启用了cors并添加了启用cors属性,但仍然出现错误: No 'Access-Control-Allow-Origin' header is present …我也尝试过特定网站,但仍然是同样的错误。 我正在使用Visual Studio 2013 .Net Framework 4.5。

我可以通过与asp.net-web-api在同一网站上的html访问资源

码:

HTML :

     function GetAllStudents() { $.ajax({         type: "GET", url: "http://localhost/studentsWebapi/students", success: function(result) { var list = $("#students"); for (var i = 0; i < result.length; i++) { var students = result[i]; list.append('
  • ' + student.FirstName + '
  • '); } }, error: function(xhr) { alert("here " + xhr.responseText); } }); }
    here
    click me

    由于某些问题,我无法执行您的项目,但我做了一个示例项目,通过HttpResponseMessage类演示解决方案。

    您可以使用HttpResponseMessage类。 然后,您可以在需要时在响应标头中添加Access-Control-Allow-Origin: *

     public HttpResponseMessage GetStudents() { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, StudentRepository.GetAllStudents()); response.Headers.Add("Access-Control-Allow-Origin", "*"); return response; } 

    保持项目结构是一种很好的做法。 我已经对你的项目进行了一些修改以使其变得低俗。

    在此处输入图像描述

    1. WebAPI项目。

    App_Start / WebApiConfig.cs:我已配置: routeTemplate: "api/{controller}/{action}/{id}"根据此模式发出请求。 示例: http://localhost:60604/api/students/getstudents

     using System.Web.Http; namespace WebAPI { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } } } 

    库/ StudentRepository.cs:

     using System.Collections.Generic; using System.Linq; using WebAPI.Models; namespace WebAPI.Repository { public class StudentRepository { private static List students = new List { new Student(){ StudentID=1, FirstName="Hass",LastName="Moh"}, new Student(){ StudentID=2, FirstName="Hassan",LastName="Mohemm"}, new Student(){ StudentID=3, FirstName="Hussan",LastName="Mohu"}, new Student(){ StudentID=4, FirstName="Hessan",LastName="Moham"} }; public static List GetAllStudents() { return students; } public static Student GetStudent(int studentID) { return students.Where(d => d.StudentID == studentID).First(); } public static void RemoveStudent(int studentID) { var stu = students.Find(s => s.StudentID == studentID); students.Remove(stu); } public static void AddStudent(Student student) { students.Add(student); } public static void UpdateStudent(Student student) { // } } } 

    型号/ Student.cs:

     namespace WebAPI.Models { public class Student { public int StudentID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } } 

    API / StudentsController.cs:

     using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using WebAPI.Models; using WebAPI.Repository; namespace WebAPI.API { public class StudentsController : ApiController { public List Get() { return StudentRepository.GetAllStudents(); } public HttpResponseMessage GetStudents() { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, StudentRepository.GetAllStudents()); response.Headers.Add("Access-Control-Allow-Origin", "*"); return response; } public Student Get(int id) { return StudentRepository.GetStudent(id); } public void Post(Student Student) { StudentRepository.AddStudent(Student); } public void Put(Student Student) { StudentRepository.UpdateStudent(Student); } public void Delete(int id) { StudentRepository.RemoveStudent(id); } } } 

    2. WebApplication项目。

    index.html的:

             

      然后,我们可以得到下一个结果。 在此处输入图像描述

      希望这可以帮助。