I cannot access resources in asp.net-web-api with ajax . I enabled cors for all requests and added enable cors attribute but still get error: No 'Access-Control-Allow-Origin' header is present
... I also tried it with a particular website but still the same error. I am using Visual Studio 2013 .Net Framework 4.5.
I can access resourse with html sitting in the same website as asp.net-web-api
Code:
html :
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> 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('<li>' + student.FirstName + '</li>'); } }, error: function(xhr) { alert("here " + xhr.responseText); } }); } </script> </head> <body> <div id="data"> here <ol id="students"> </ol> <input type="button" onClick="GetAllStudents()"> click me </input> </div> </body> </html>
I could not execute your project due some issues but I did an example project to demonstrate a solution through the HttpResponseMessage
class.
You can use HttpResponseMessage
class. Then you can add the Access-Control-Allow-Origin: *
in the response headers when you need.
public HttpResponseMessage GetStudents()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, StudentRepository.GetAllStudents());
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
It's a good practice to keep a project structure. I've made some changes in your project to make understable.
1. WebAPI project.
App_Start/WebApiConfig.cs: I've configured: routeTemplate: "api/{controller}/{action}/{id}"
to make requests according this schema. Example: 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 }
);
}
}
}
Repository/StudentRepository.cs:
using System.Collections.Generic;
using System.Linq;
using WebAPI.Models;
namespace WebAPI.Repository
{
public class StudentRepository
{
private static List<Student> students = new List<Student> {
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<Student> 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)
{
//
}
}
}
Models/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<Student> 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 project.
index.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="data">
<ol id="students"></ol>
<input type="button" value=" click me" />
</div>
<script>
$(function ()
{
$.ajax({
type: "GET",
url: "http://localhost:60604/api/students/getstudents",
success: function (result)
{
var list = $("#students"), student, html = "", len = result.length;
for (var i = 0; i < len; i++)
{
student = result[i];
html = "<li>";
html += student.FirstName;
html += "</li>";
list.append(html);
}
},
error: function (xhr)
{
alert("here " + xhr.responseText);
}
});
});
</script>
</body>
</html>
Then, we can get the next results.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.