【发布时间】:2015-09-23 01:06:50
【问题描述】:
目前正在处理一个调用我的 SQL 服务器的 rest api 的网页。在 VS2013 中的本地主机上工作,但是当发布并添加到服务器时,我开始遇到 CORS 问题。我已将以下代码添加到我的 web.config 文件中以用于我的 Web 服务,但仍然没有运气:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
启用 Cors 后,我的 webapiconfig.cs 如下所示:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ContractResolver = new
CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
}
}
我的控制器文件也有正确的 CORS 头:
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class RefurbItemsController : ApiController
{
// GET: api/RefurbItems
[Route("api/RefurbItems")]
public HttpResponseMessage Get()
{
var items = RefurbItems.GetAllItems();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, items);
return response;
}
// GET: api/RefurbItems/5
public string Get(int id)
{
return "value";
}
// POST: api/RefurbItems
public void Post([FromBody]string value)
{
}
// PUT: api/RefurbItems/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/RefurbItems/5
public void Delete(int id)
{
}
}
它在我的开发机器和服务器本身上本地运行良好,但是当我尝试将它部署到网络并查看页面时,我收到以下错误消息: 在 Access-Control-Allow-Origin 标头中找不到来源。 XMLHttpRequest:网络错误 0x80070005,访问被拒绝。
如果有人可以提供一些想法或任何我愿意尝试的东西,我是 asp.net 的新手
【问题讨论】:
-
您似乎打开了 GET 方法。哪个 http 请求出现此错误?
-
GET 收到此错误,这是我尝试运行的唯一方法。我只是想从我的 sql 服务器返回一个值列表,然后在选择时使用 $scope 将它们传递给一个联系表单。在 VS2013 的本地调试中一切正常,但在部署到网络时却无法正常工作
标签: c# asp.net angularjs rest cors