CORAP与WebAPI有时有效,有时则无效

时间:2013-07-08 23:02:06

标签: asp.net-web-api cors asp.net-web-api-routing

我使用了以下内容:

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

正如这里建议的那样:

Enabling CORS with WebAPI PUT / POST requests?

在我的项目中启用跨源AJAX请求。一切(POST / PUT / DELETE / GET)昨天都在运行。然后我决定在我的webAPI项目中添加一个新的端点,这个端点失败了:

> XMLHttpRequest cannot load http://localhost:24144/api/card. Origin
> http://localhost:11089 is not allowed by Access-Control-Allow-Origin.

在我的WebApiConfig中,我做到了这一点:

        var cors = new EnableCorsAttribute("http://localhost:11089", "*", "*");
        config.EnableCors(cors);

我的AJAX请求与其他正在运行的请求相同,如下所示:

 var updateCard = function (data) {
        var options = {
            url: apiEndpoint + 'card',
            type: 'PUT',
            async: true,
            dataType: 'json',
            data: data,
            xhrFields: {
                withCredentials: true
            }
        };

        return $.ajax(options)
            .done(function (response) {
                toastr.success("Card Updated", "Success");
            })
            .fail(function (msg) {
                toastr.error("Could not update card.", "Error");
            });
    }
};

即使直接在失败的方法或控制器上使用该属性,我也会得到同样的错误:

 [EnableCors(origins: "http://localhost:11089", headers: "*", methods: "*")]

为什么会这样?我注意到如果我在调试时杀了我的webAPI解决方案,我在客户端会遇到相同的错误,但它通常只发生一次,并且预期的行为会随着WebAPI项目重新开始。这不是问题,但可能是相关的。

如果你认为我应该提供其他任何内容,请告诉我。

更新:堆叠:

     iisexpress.exe Information: 0 : Request, Method=OPTIONS, Url=http://localhost:24144/api/card, Message='http://localhost:24144/api/card'
iisexpress.exe Information: 0 : Message='Card', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='Selected action 'UpdateCard(CardDto card)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Message='CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'', Operation=AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider
iisexpress.exe Information: 0 : Message='CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: False, PreflightMaxAge: null, SupportsCredentials: False, Origins: {http://localhost:11089}, Methods: {}, Headers: {}, ExposedHeaders: {}'', Operation=EnableCorsAttribute.GetCorsPolicyAsync
iisexpress.exe Information: 0 : Message='CorsResult returned: 'IsValid: True, AllowCredentials: False, PreflightMaxAge: null, AllowOrigin: http://localhost:11089, AllowExposedHeaders: {}, AllowHeaders: {accept,origin,content-type}, AllowMethods: {PUT}, ErrorMessages: {}'', Operation=CorsEngine.EvaluatePolicy
iisexpress.exe Information: 0 : Operation=CorsMessageHandler.SendAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Response, Status=200 (OK), Method=OPTIONS, Url=http://localhost:24144/api/card, Message='Content-type='none', content-length=unknown'
iisexpress.exe Information: 0 : Request, Method=PUT, Url=http://localhost:24144/api/card, Message='http://localhost:24144/api/card'
iisexpress.exe Information: 0 : Message='Card', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='App.Service.Controllers.CardController', Operation=DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message='App.Service.Controllers.CardController', Operation=HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message='Selected action 'UpdateCard(CardDto card)'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Operation=AuthorizeAttribute.OnAuthorization
iisexpress.exe Information: 0 : Message='Value read='App.Repository.Models.Dtos.CardDto'', Operation=JQueryMvcFormUrlEncodedFormatter.ReadFromStreamAsync
iisexpress.exe Information: 0 : Message='Parameter 'card' bound to the value 'App.Repository.Models.Dtos.CardDto'', Operation=FormatterParameterBinding.ExecuteBindingAsync
iisexpress.exe Information: 0 : Message='Model state is valid. Values: card=App.Repository.Models.Dtos.CardDto', Operation=HttpActionBinding.ExecuteBindingAsync
A first chance exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Message='Action returned 'StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
  Content-Type: application/json; charset=utf-8
}'', Operation=ReflectedHttpActionDescriptor.ExecuteAsync
iisexpress.exe Information: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Operation=CardController.ExecuteAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Message='CorsPolicyProvider selected: 'System.Web.Http.Cors.EnableCorsAttribute'', Operation=AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider
iisexpress.exe Information: 0 : Message='CorsPolicy selected: 'AllowAnyHeader: True, AllowAnyMethod: True, AllowAnyOrigin: False, PreflightMaxAge: null, SupportsCredentials: False, Origins: {http://localhost:11089}, Methods: {}, Headers: {}, ExposedHeaders: {}'', Operation=EnableCorsAttribute.GetCorsPolicyAsync
iisexpress.exe Information: 0 : Message='CorsResult returned: 'IsValid: True, AllowCredentials: False, PreflightMaxAge: null, AllowOrigin: http://localhost:11089, AllowExposedHeaders: {}, AllowHeaders: {}, AllowMethods: {}, ErrorMessages: {}'', Operation=CorsEngine.EvaluatePolicy
iisexpress.exe Information: 0 : Operation=CorsMessageHandler.SendAsync, Status=500 (InternalServerError)
iisexpress.exe Information: 0 : Response, Status=500 (InternalServerError), Method=PUT, Url=http://localhost:24144/api/card, Message='Content-type='application/json; charset=utf-8', content-length=unknown'
iisexpress.exe Error: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync, Exception=Newtonsoft.Json.JsonSerializationException: Error getting value from 'Stage' on 'System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42'. ---> System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
   at System.Data.Objects.ObjectContext.EnsureConnection()
   at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
   at System.Data.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)
   at System.Data.Objects.DataClasses.RelatedEnd.Load()
   at System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad()
   at System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
   at System.Data.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)
   at System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42.get_Stage()
   at GetStage(Object )
   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
   --- End of inner exception stack trace ---
   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IWrappedCollection values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value)
   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)
   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__33.MoveNext()
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=CardController.Dispose

2 个答案:

答案 0 :(得分:0)

如果有其他人碰到这个并且碰巧使用工作单位和来自WebAPI2的CORS与EF(ha) -

我有一个延迟加载的属性,在执行Update方法时不可用。我不知道为什么抛出的错误是不准确的,但是堆栈跟踪指向了正确的方向:

  

从'Stage'获取值时出错   'System.Data.Entity.DynamicProxies.Sid​​e_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42'。   ---&GT; System.ObjectDisposedException:ObjectContext实例已被释放,不能再用于需要的操作   连接。

答案 1 :(得分:-1)

如果您使用的是IIS 7.5或更低版本,请使用此配置

<system.webServer>
    <handlers>
     <remove name="OPTIONSVerbHandler"/>
  </handlers>
 </system.webServer>

或者如果您使用的是IIS 8或更高版本

<system.webServer>
    <handlers>
        <remove name="OPTIONS"/>
     </handlers>
</system.webServer>

希望这个帮助