JsonResult Response from WebAPI for Elasticsearch NEST query - elasticsearch

I have created WEBAPI methods, to search ES using NEST. The search with ES is working as expected. The issue that I have is when I try to return the Json(response) using POSTMAN, it throws this exception:
{
"Message": "An error has occurred.",
"ExceptionMessage": "If you use a custom contract resolver be sure to subclass from ElasticContractResolver",
"ExceptionType": "System.Exception",
"StackTrace": " at Nest.JsonExtensions.GetConnectionSettings(JsonSerializer
serializer)\r\n at
Nest.VerbatimDictionaryKeysJsonConverter2.WriteJson(JsonWriter
writer, Object value, JsonSerializer serializer)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter
writer, JsonConverter converter, Object value, JsonContract contract,
JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter
writer, Object value, JsonObjectContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
System.Web.Http.Results.JsonResult1.Serialize()\r\n at
System.Web.Http.Results.JsonResult1.Execute()\r\n at
System.Web.Http.Results.JsonResult1.ExecuteAsync(CancellationToken
cancellationToken)\r\n at
System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Controllers.AuthenticationFilterResult.d__0.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
}
This is my WEB API method
[System.Web.Http.Route("SearchElastic")]
[System.Web.Http.HttpPost]
public JsonResult<ISearchResponse<T>> SearchElastic([FromBody] ElasticSearchRequest esRequest)
{
var searchResponse = EsClient.Search<T>(
"...NEST query..."
));
return Json(searchResponse);
}
//<T> is a custom C# class.
I am using Elasticsearch/NEST 5.x.

The error message hints at what the problem is
{ "Message": "An error has occurred.", "ExceptionMessage": "If you use
a custom contract resolver be sure to subclass from
ElasticContractResolver", "ExceptionType": "System.Exception",
"StackTrace": " at ...
and it relates to the line
return Json(searchResponse);
the configuration for the Json serializer used by Web API does not know how to handle serializing certain types from NEST because some of those types need ElasticContractResolver to be serialized correctly.
There are a few ways to solve this, but the two most straightforward are:
Configure the Json Serializer used by Web API with ElasticContractResolver as the IContractResolver on the JsonSerializerSettings. The disadvantage here is that all of your types that you're serializing to json will be going through NEST's resolver
Avoid the deserialization/re-serialization loop from Elasticsearch -> deserialized by NEST -> reserialized by Web API altogether by using the low level client to return a string or byte array from Elasticsearch. I would recommend this approach if you are not doing any introspection on searchResponse. If you do need to inspect searchResponse, you can always deserialize the string or byte array to SearchResponse<T> as a separate step.
This is one of the reasons that the direct dependency on Json.NET has been removed in NEST 6.x

Related

I am trying to create a action card using CDS but facing below issue on request

Body Content:
{
"#odata.context": "https://aaaaaaaaaaaaaaaaa.crm.dynamics.com/api/data/v9.0/$metadata#actioncards/$entity",
"_cardtypeid_value#OData.Community.Display.V1.FormattedValue": "CloseDateComingSoon",
"_cardtypeid_value#Microsoft.Dynamics.CRM.associatednavigationproperty": "cardtypeid",
"_cardtypeid_value#Microsoft.Dynamics.CRM.lookuplogicalname": "cardtype",
"_cardtypeid_value": "c16b8555-d33a-4e98-8188-1b123efbd4e9",
"_ownerid_value#OData.Community.Display.V1.FormattedValue": "Sudhakar Marreddy",
"_ownerid_value#Microsoft.Dynamics.CRM.associatednavigationproperty": "ownerid",
"_ownerid_value#Microsoft.Dynamics.CRM.lookuplogicalname": "systemuser",
"_ownerid_value": "f6fa6fa7-0bac-e711-8114-c4346bdca111",
"msdyn_regardingobjectid": "77af6f8e-f55d-e811-a83d-000d3a1bbafa",
"expirydate": "2020-06-27T21:36:05Z",
"priority": 400,
"source": 1,
"startdate": "2020-05-19T01:36:05Z",
"state": 0,
"visibility": true,
"title": "TestingRACards_5/19_via_postman",
"description": "This Works! RA Cards created successfullt from Postman"
}
Result :
{
"error": {
"code": "0x0",
"message": "CRM do not support direct update of Entity Reference properties, Use Navigation properties instead.",
"innererror": {
"message": "CRM do not support direct update of Entity Reference properties, Use Navigation properties instead.",
"type": "Microsoft.Crm.CrmHttpException",
"stacktrace": " at Microsoft.Crm.Extensibility.OData.TypeConverters.EntityReferenceAttributeTypeConverter.ConvertToCrmTypeInternal(Guid edmTypeValue, String operationName)\r\n at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmTypeConverterBase`2.ConvertToCrmType(Object edmTypeValue, String operationName)\r\n at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmEntityTypeConverter.SetStructuralPropertyToXrmEntity(Entity entity, EntityMetadata entityMetadata, String crmAttributeName, IEdmProperty edmProperty, Object propertyValue)\r\n at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmEntityTypeConverter.ConvertToCrmTypeInternal(EdmEntityObject edmTypeValue, String operationName)\r\n at Microsoft.Crm.Extensibility.OData.TypeConverters.EdmTypeConverterBase`2.ConvertToCrmType(Object edmTypeValue, String operationName)\r\n at Microsoft.Crm.Extensibility.OData.EdmTypeConverter.ConvertToCrmEntity(EdmEntityObject edmEntity, EntityReference entityReference, IEdmModel edmModel)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.CreateEdmEntity(CrmODataExecutionContext context, String edmEntityName, EdmEntityObject entityObject, Boolean isUpsert)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.PostEntitySetImplementation(String& entitySetName, EdmEntityObject entityObject)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataUtilities.<>c__DisplayClass10_0`2.<InvokeActionAndLogMetric>b__0()\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
"msdyn_regardingobjectid": "77af6f8e-f55d-e811-a83d-000d3a1bbafa",
Instead of this line, you should get something similar to _ownerid_value for _regardingobjectid_value. So some simple assignment issue.
Use this below snippet for assignment of regardingobjectid lookup: (make sure you are using correct entity in place of accounts)
"regardingobjectid#odata.bind": "/accounts(77af6f8e-f55d-e811-a83d-000d3a1bbafa)",

Error occurs when try to implement virtual entity in MS CRM - An OData error occurred

I am trying to implement Virtual Entity in CRM Online V9.1.0.5220. I have created custom ODATA services below are the screenshots -
I have created Bank virtual entity in CRM, when I am trying to call the virtual entity I am getting following error 'Entity could not be retrieved from data source. Please try again or contact your system administrator.'
When I am trying to call the virtual entity from browser as /api/data/v9.1/geo_banks, I am getting below error -
{
"error": {
"code": "0x80050263",
"message": "An OData error occurred.",
"innererror": {
"message": "An OData error occurred.",
"type": "System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=9.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]",
"stacktrace": " at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.RetrieveMultiple(QueryBase query, InvocationContext invocationContext, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Guid appModuleId, Dictionary`2 optionalParameters)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.RetrieveMultiple(QueryBase query)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.RetrieveEdmEntityCollection(CrmODataExecutionContext context, String entityCollectionName, String castedEntityName, ODataQueryOptions queryOptions)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.<>c__DisplayClass35_0.<GetEntitySetInternal>b__1()\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute(ILogger logger, EventId eventId, ActivityType activityType, Action action, IEnumerable`1 additionalCustomProperties)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute(ILogger logger, XrmTelemetryActivityType activityType, Action action)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.GetEntitySetInternal(String entitySetName, String castedEntityName, CrmODataExecutionContext context, CrmEdmEntityObjectCollection crmEdmEntityObjectCollection, ODataQueryOptions queryOptions)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.GetEntitySetImplementation(String entitySetName)\r\n at Microsoft.PowerApps.CoreFramework.ActivityLoggerExtensions.Execute[TResult](ILogger logger, EventId eventId, ActivityType activityType, Func`1 func, IEnumerable`1 additionalCustomProperties)\r\n at Microsoft.Xrm.Telemetry.XrmTelemetryExtensions.Execute[TResult](ILogger logger, XrmTelemetryActivityType activityType, Func`1 func)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
I have tried to consume https://services.odata.org/V4/OData/OData.svc/ ODATA service and it is working as expected.
I know the issue is with the service but couldn't figure out the exact reason as both the services are similar.

Updating stageid of a Dynamics CRM entity using the OData API resulting in Invalid Cast exception

I am trying to update the stageid of the Business process Workflow(BPF) enabled entity in attempt to move the next stage using the Odata api.
Below is my HTTP request details
[organization]/api/data/v8.1/MyEntity(0df630c1-3e1e-e811-810f-3863bb35ed38)
Method :- Patch
Body :-
{"stageid#odata.bind":"/processstages(0e603558-a5e2-176b-6c18-3b498377ab12)","traversedpath":"4625784d-7813-4e07-aef5-a7e3f231219f,0e603558-a5e2-176b-6c18-3b498377ab12"}
But, my request fails with invalid cast exception.
{
"error":{
"code":"","message":"System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #E6D73AE1","innererror":{
"message":"System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #E6D73AE1","type":"System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]","stacktrace":" at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Update(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, Boolean checkAdminMode, Boolean checkForOptimisticConcurrency, Dictionary`2 optionalParameters)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataExecutionContext.Update(Entity entity, UpdateOption updateOption)\r\n at Microsoft.Crm.Extensibility.OData.CrmODataServiceDataProvider.UpdateEdmEntity(CrmODataExecutionContext context, String edmEntityName, String entityKeyValue, EdmEntityObject entityObject)\r\n at Microsoft.Crm.Extensibility.OData.EntityController.PatchEntity(String entityName, String key, EdmEntityObject entityDelta)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
}
}
Any help on what i might be doing wrong here? I usually use the #odata.bind for the lookups, but stageid seems to be of type Unique identifier. how do i update a unique identifier?
Also, it would be really helpful to know how can one debug or know more details about this administrator reference numbers.
P.S:- I know updating the stageid can be achieved using the CRM SDK's, but i din't find any help doing the same with the odata API.
Techically stageid is just a guid and not a lookup. Try to update your entity using following payload:
{"stageid":"0e603558-a5e2-176b-6c18-3b498377ab12"}

Botstate.SetConversationData - Unexpected character encountered while parsing value

I am trying to save conversation data via state client and I am getting inconsistent results between the emulator and the sms channels. Testing my bot app via emulator allows me to SetConversationData and GetConversationData fine, but as soon as I try it on sms with service url: https://sms.botframework.com/ I get the following error:
"exceptionMessage": "Unable to deserialize the response.",
"exceptionType": "Microsoft.Rest.SerializationException",
"stackTrace": " at Microsoft.Bot.Connector.BotState.d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Bot.Connector.BotStateExtensions.d__9.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Bot.Connector.BotStateExtensions.SetConversationData(IBotState operations, String channelId, String conversationId, BotData botData)\r\n at OutboundTestApp.Controllers.OutboundController.Post(OutboundConversationData`1 outboundData)",
"innerException": {
"message": "An error has occurred.",
"exceptionMessage": "Unexpected character encountered while parsing value: T. Path '', line 0, position 0.",
"exceptionType": "Newtonsoft.Json.JsonReaderException",
"stackTrace": " at Newtonsoft.Json.JsonTextReader.ParseValue()\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\r\n at Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject[T](String json, JsonSerializerSettings settings)\r\n at Microsoft.Bot.Connector.BotState.d__9.MoveNext()"
Here is my code to set the data where the channelId is "sms", conversationId is a valid id and the data is just a simple POCO class:
var stateClient = new StateClient(new Uri(serviceUrl), account);
stateClient.BotState.SetConversationData(outboundData.ChannelId, conversationResponse.Id, new BotData(data: outboundData.Data));
Should I be using SetPrivateConversationDataWithHttpMessagesAsync and pass in the content type and set my botdata to a json string? I feel the state client is assuming json is being passed somewhere, but the object it is deserializing is actually not json.
The problem is that the serviceUrl was set incorrectly when creating the state client. The baseUri should be https://state.botframework.com.

CORS with WebAPI sometimes works, sometimes doesn't

I've used the following:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
As suggested here:
Enabling CORS with WebAPI PUT / POST requests?
to enable cross-origin AJAX requests in my project. Everything (POST / PUT / DELETE / GET) was working yesterday. Then I decided to add a new endpoint to my webAPI project, and this one is failing with:
> XMLHttpRequest cannot load http://localhost:24144/api/card. Origin
> http://localhost:11089 is not allowed by Access-Control-Allow-Origin.
In my WebApiConfig I've done this:
var cors = new EnableCorsAttribute("http://localhost:11089", "*", "*");
config.EnableCors(cors);
And my AJAX request, identical to others that are working, looks like this:
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");
});
}
};
Even if use the attribute directly on the method or controller that's failing, I get the same error:
[EnableCors(origins: "http://localhost:11089", headers: "*", methods: "*")]
Why would this be happening? I noticed that if I kill my webAPI solution while debugging, I get the same error in the client, but it usually only happens once and expected behavior resumes with the WebAPI project. This isn't a problem but maybe it's relevant.
If there's anything else you think I should provide here, let me know.
Update: Stack:
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
In case anyone else runs into this and happens to be using Unit Of Work and CORS from WebAPI2 with EF (ha) -
I had a lazily-loaded property that was not available when the Update method was executing. I don't know why the error thrown was inaccurate, but the stack trace pointed me in the right direction:
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.
If you are using IIS 7.5 or below use this config
<system.webServer>
<handlers>
<remove name="OPTIONSVerbHandler"/>
</handlers>
</system.webServer>
Or if you are using IIS 8 or above
<system.webServer>
<handlers>
<remove name="OPTIONS"/>
</handlers>
</system.webServer>
Hope this help

Resources