我在MVC中有一个API。它配置如下:ASP.NET MVC API发布数据
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "API/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
我使用自定义的路由我的API,使RESTful服务的一个例子是以下控制器
[RoutePrefix("datapi/user")]
public class UserController : ApiController
{
[EnableCors("*", "*", "*")]
[Route("getuser/{userid}/")]
[System.Web.Http.HttpGet]
public ObjUser GetUserObject(string userid)
{
ObjUser user = this.userdata.GetUser(userid);
return user;
}
[EnableCors("*", "*", "*")]
[Route("updatepassword")]
[System.Web.Http.HttpPost]
public ObjUser UpdateUserPassword(string userid, string password)
{
ObjUser user = this.userdata.GetUser(userid);
user.Password = password;
this.userdata.SaveUser(user);
return user;
}
}
的“的getUser”法正常工作。我在我的应用程序中获得Json格式的对象
当我使用HttpPost服务(updatepassword)时出现问题。我试图通过HttpPost发送数据,它给了我一个CORS错误,说
“跨来源请求阻止:同源策略不允许 读取远程资源”
有什么问题与我的配置?
以下是测试我有两个
$.ajax({
url: 'http://localhost:3351/datapi/user/updatepassword'
type: 'POST',
data: {
userid: '[email protected]',
password: 'newpassword'
},
contentType: 'application/json',
success: function(data) {
console.log(data);
}
});
$.ajax({
url: 'http://localhost:3351/datapi/user/getuser/[email protected]'
type: 'GET',
contentType: 'application/json',
success: function(data) {
console.log(data);
}
});
编辑完成:多个测试结果
所以我有预感,我测试用的服务如下:
$.ajax({
url: 'http://localhost:3351/datapi/user/updatepassword/[email protected]/somepassword'
type: 'POST',
contentType: 'application/json',
success: function(data) {
console.log(data);
}
});
这工作。但是,如果输入中的任何一个包含冒号“:”,则会发出CORS错误!前进的道路是两条路径,一条限制输入“:”,另一条将其转换为unicode。这个API很安静,但其他一些人建议将Ajax数据中的数据作为有效载荷提供,这将与restful api一起工作吗?
您是否在ajax请求中将'crossDomain'设置为'true'?尝试一下 – Madhu 2015-03-13 06:18:34
我需要吗?我在MVC中使用EnableCors并且getuser工作得很好为什么是 – progrAmmar 2015-03-13 06:21:04