Angular.js - CORS - ASP. NET - Rest API -在Access-Control-All
本文关键字:API Rest Access-Control-All ASP js CORS Angular NET | 更新日期: 2023-09-27 18:01:18
目前正在一个网页上工作,它调用了一个rest api,它击中了我的SQL服务器。在VS2013的本地主机上工作,但是当发布并添加到服务器时,我开始遇到CORS问题。我已经添加了以下代码到我的网页。我的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)
{
}
}
它在我的开发机器和服务器本身的本地运行良好,但是当我试图将它部署到web并查看页面时,我得到以下错误消息:在Access-Control-Allow-Origin头文件中找不到Origin。XMLHttpRequest: Network Error 0x80070005, Access is denied.
如果有人可以帮助一些想法或任何我开放尝试我是新的asp.net
原来的问题是,我有EnableCors位于2个位置,它是在类和控制器:
WebApiConfig.cs
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);
控制器[EnableCors(origins: "*", headers: "*", methods: "*")]
我所要做的就是删除位于WebApiConfig.cs中的config.EnableCors(),一切都开始正常工作。