使用WebAPI的CORS有时能用,有时不能用。

问题描述 投票:6回答:2

我用的是下面的。

http:/www.asp.netweb-apioverviewsecurityenabling-cross-origin-requests-in-web-api

正如这里的建议。

用WebAPI PUT POST请求启用CORS?

以便在我的项目中启用跨源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
asp.net-web-api asp.net-web-api-routing
2个回答
0
投票

以防有人遇到这种情况,并且碰巧在使用EF的WebAPI2的Unit Of Work和CORS(哈)--。

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

错误地从'System.Data.Entity.DynamicProxies.Side_F7B85DBC8AA69F5AAA5ACCA92A66F2763E57D4D2046F02AC7EE6064A3409DE42'上的'Stage'获取值。 ---> System.ObjectDisposedException: ObjectContext实例已经被处置,不能再用于需要连接的操作。


-1
投票

如果你使用的是IIS 7.5或以下版本,请使用以下配置。

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

或者,如果您使用的是IIS 8或以上的版本

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

希望能帮到你

© www.soinside.com 2019 - 2024. All rights reserved.