Quantcast
Channel: ASPNETWebStack Issue Tracker Rss Feed
Viewing all 7215 articles
Browse latest View live

Edited Issue: Razor V2 Bug:Url Resolution Fails if you have Html Comment with Quotation or Apostrophe [933]

$
0
0
During discussing a thread in ASP.NET MVC forums, found a bug in Razor V2 in which the auto url resolution(~) will not work if you have an html comment with quotation or apostrophe before the url resolution(~) tag. Here is an quick example,
``` Html
<!-- '" -->
<img src="~/images/submit.png" />
```

See this thread,
[http://forums.asp.net/t/1892597.aspx/1?Using+UrlHelper+Content](http://forums.asp.net/t/1892597.aspx/1?Using+UrlHelper+Content)

Created Unassigned: OData $batch fails with WCF DS client [1135]

$
0
0
with exception,

Unhandled Exception: System.Data.Services.Client.DataServiceRequestException: An
error occurred while processing this request. ---> System.Data.Services.Client.
DataServiceClientException: <Error><Message>No HTTP resource was found that matc
hes the request URI 'http://localhost:8080/http://localhost:8080/Customers(42)/O
rders'.</Message><MessageDetail>No route data was found for this request.</Messa
geDetail></Error>


I think the problem is in the content-id to uri translation.

Commented Issue: TransferEncodingChunked=true doesn't work on WebHost [1124]

$
0
0
When setting response.Headers.TransferEncodingChunked, the response doesn't get chunked, and a client (Fiddler) will fail trying to read the response.

Repro 1:
public HttpResponseMessage Get()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.TransferEncodingChunked = true;
response.RequestMessage = Request;
return response;
}

Repro 2:
public HttpResponseMessage Get()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new LazyContent();
response.Headers.TransferEncodingChunked = true;
response.RequestMessage = Request;
return response;
}

public class LazyContent : HttpContent
{
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
stream.WriteByte(0);
return Task.FromResult<object>(null);
}

protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}

Comments: The problem actually repros regardless of the buffering policy. I've tried both of the following options: config.Services.Replace(typeof(IHostBufferPolicySelector), new AlwaysBufferPolicySelector()); config.Services.Replace(typeof(IHostBufferPolicySelector), new NeverBufferPolicySelector()); private class NeverBufferPolicySelector : IHostBufferPolicySelector { public bool UseBufferedInputStream(object hostContext) { return false; } public bool UseBufferedOutputStream(System.Net.Http.HttpResponseMessage response) { return false; } } private class AlwaysBufferPolicySelector : IHostBufferPolicySelector { public bool UseBufferedInputStream(object hostContext) { return false; } public bool UseBufferedOutputStream(System.Net.Http.HttpResponseMessage response) { return false; } } Without that the following header set, the buffer policy selector does control chunking: response.Headers.TransferEncodingChunked = true; But with that header set, the response is not handled correctly with either of the buffer policies above.

Commented Issue: TransferEncodingChunked=true doesn't work on WebHost [1124]

$
0
0
When setting response.Headers.TransferEncodingChunked, the response doesn't get chunked, and a client (Fiddler) will fail trying to read the response.

Repro 1:
public HttpResponseMessage Get()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.TransferEncodingChunked = true;
response.RequestMessage = Request;
return response;
}

Repro 2:
public HttpResponseMessage Get()
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new LazyContent();
response.Headers.TransferEncodingChunked = true;
response.RequestMessage = Request;
return response;
}

public class LazyContent : HttpContent
{
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
stream.WriteByte(0);
return Task.FromResult<object>(null);
}

protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}

Comments: The buffer policy of the host correctly/smartly handles the situation of whether a response should be chunked or not based on the existing logic…so ideally the user needn’t set the chunked encoding property explicitly… For example: if the content is already buffered (ex: downloading a file from the disk), then according to our policy, we do not send it chunked as we already know the content-length...in this case using chunked transfer encoding doesn’t make sense…If I remember correctly, we are supposed to send chunked encoding only when we do not know the content length upfront...for example, if we are streaming data from the service to the client as the data is received at the service from some other party (PushStreamContent example)…in case of PushStreamContent, we correctly set the chunked encoding header… So, for any custom httpcontent that user creates, they would need to extend the buffer policy to either send data in chunked or non-chunked.

Commented Unassigned: OData $batch fails with WCF DS client [1135]

$
0
0
with exception,

Unhandled Exception: System.Data.Services.Client.DataServiceRequestException: An
error occurred while processing this request. ---> System.Data.Services.Client.
DataServiceClientException: <Error><Message>No HTTP resource was found that matc
hes the request URI 'http://localhost:8080/http://localhost:8080/Customers(42)/O
rders'.</Message><MessageDetail>No route data was found for this request.</Messa
geDetail></Error>


I think the problem is in the content-id to uri translation.
Comments: The problem is occurring because the dataservices client formats it sub-request URI's as full URI's, ie: http://localhost:8080/$2/Orders Later, the content id mapping process replaces the content id with the full URI to the new resource: ie: http://localhost:8080/Customers(42) resulting in the invoker trying to execute http://localhost:8080/http://localhost:8080/Customers(42)/Orders I have a work-around that was posted in VB as part of a different problem I am having which Kiren is helping me with. Basically checks for content id's in the URI's during the parse, and makes the URI relative before returning. They appear to be unrelated, but I thought I'd offer my insight. http://stackoverflow.com/questions/17667575/web-api-odata-batch-fails-after-update-to-nightly-build-july-15 Hope it is useful. Steve

Commented Unassigned: OData $batch fails with WCF DS client [1135]

$
0
0
with exception,

Unhandled Exception: System.Data.Services.Client.DataServiceRequestException: An
error occurred while processing this request. ---> System.Data.Services.Client.
DataServiceClientException: <Error><Message>No HTTP resource was found that matc
hes the request URI 'http://localhost:8080/http://localhost:8080/Customers(42)/O
rders'.</Message><MessageDetail>No route data was found for this request.</Messa
geDetail></Error>


I think the problem is in the content-id to uri translation.
Comments: Apologies for not using preview.

Created Issue: Unbuffered input streams don't work correctly on web host [1136]

$
0
0
Returning false from IHostBufferPolicySelector.UseBufferedInputStream on web host breakes Web API + MVC side-by-side, at least in some scenarios.

Consider an MVC controller with the following code:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Test = new StreamReader(Request.InputStream).ReadToEnd();
return View();
}
}

Then, have in the same web app the following Web API setup:
public static void Register(HttpConfiguration config)
{
config.Services.Replace(typeof(IHostBufferPolicySelector), new BufferOutputOnlyPolicySelector());
config.Routes.Add("Unused", new CustomRoute());
}

private class BufferOutputOnlyPolicySelector : IHostBufferPolicySelector
{
public bool UseBufferedInputStream(object hostContext)
{
return false;
}

public bool UseBufferedOutputStream(System.Net.Http.HttpResponseMessage response)
{
return true;
}
}

private class CustomRoute : IHttpRoute
{
public IDictionary<string, object> Constraints
{
get { return null; }
}

public IDictionary<string, object> DataTokens
{
get { return null; }
}

public IDictionary<string, object> Defaults
{
get { return null; }
}

public IHttpRouteData GetRouteData(string virtualPathRoot, System.Net.Http.HttpRequestMessage request)
{
return null;
}

public IHttpVirtualPathData GetVirtualPath(System.Net.Http.HttpRequestMessage request, IDictionary<string, object> values)
{
return null;
}

public System.Net.Http.HttpMessageHandler Handler
{
get { return null; }
}

public string RouteTemplate
{
get { return null; }
}
}

Then, try viewing the MVC page. You'll find that Web API routing broke MVC access to the page.

The only reason the CustomRoute is needed for the repro is some (apparent) optimizations around HostedHttpRoute that avoid creating an HttpRequestMessage. I believe adding a route constraint will also trigger the bug.

A possible solution is not to provide access to the input stream during Web API routing. (Note that the bug repros even when the input stream is not accessed during routing; merely making it available to be accessed causes this bug.)

Created Unassigned: ObjectContent.Value to return T not object [1137]

$
0
0
Currently `ObjectContext<T>` returns `base.Value` which has type `object`.
Doesn't it make sense to introduce strongly-typed property to return `T` ( and change how is being kept internally)?

Edited Issue: Returning related entities when they are null. OData Web API [1134]

$
0
0
If I try to load a related entity which is null, for instance I have my schema as Carrier has many Phones and I retrieved a Phone and I want to load the Carrier but the Carrier is null (which is ok), then I go to my Container and do "LoadProperty(Phone, "Carrier")" I get an exception because on my Web API OData I have GetCarrier in my PhonesController and when it tries to return the Carrier from this Phone which is null it throws the following error:

```
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata=minimalmetadata; streaming=true; charset=utf-8'.
```

With an inner exception of:

```
Cannot serialize a null 'entry'.
```

And a stack trace:

```
at System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteObject(Object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.<>c__DisplayClassa.<WriteToStreamAsync>b__9()
at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
--- 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.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__33.MoveNext()

```
Is this by design or should I be handling this differently?

My controller has the following method:

```
public Carrier GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

return phone.Carrier;
}
```

Or should I change my code to the following:

```
public HttpResponseMessage GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

if(phone.Carrier == null)
return Request.CreateResponse(HttpStatusCode.OK);

return Request.CreateResponse(HttpStatusCode.OK, phone.Carrier);
}
```

By doing this I won't get the error anymore when trying to user LoadProperty even if the related entity is null. Is this the correct way of doing this?

Commented Issue: Returning related entities when they are null. OData Web API [1134]

$
0
0
If I try to load a related entity which is null, for instance I have my schema as Carrier has many Phones and I retrieved a Phone and I want to load the Carrier but the Carrier is null (which is ok), then I go to my Container and do "LoadProperty(Phone, "Carrier")" I get an exception because on my Web API OData I have GetCarrier in my PhonesController and when it tries to return the Carrier from this Phone which is null it throws the following error:

```
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata=minimalmetadata; streaming=true; charset=utf-8'.
```

With an inner exception of:

```
Cannot serialize a null 'entry'.
```

And a stack trace:

```
at System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteObject(Object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.<>c__DisplayClassa.<WriteToStreamAsync>b__9()
at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
--- 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.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__33.MoveNext()

```
Is this by design or should I be handling this differently?

My controller has the following method:

```
public Carrier GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

return phone.Carrier;
}
```

Or should I change my code to the following:

```
public HttpResponseMessage GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

if(phone.Carrier == null)
return Request.CreateResponse(HttpStatusCode.OK);

return Request.CreateResponse(HttpStatusCode.OK, phone.Carrier);
}
```

By doing this I won't get the error anymore when trying to user LoadProperty even if the related entity is null. Is this the correct way of doing this?

Comments: RaghuRam, can you take a look at this?

Edited Issue: Web Api 2-OData same variable name causes type error [1128]

$
0
0
I have an odata url that is using the same variable name in two separate any clauses which causes the api to think to that the second variable (i.e. Address entity) is of the same name is of the same type as the first variable (i.e. User) and causes an error for a column not existing. I am using the web api version 2 July 8th build.

http://localhost:2351/ServtracWebPortals/Mexico/amtechcs/servtracweb/dataservice/InvoiceLines?$filter=((Invoice/Customer/Users/any(n:%20(n/Id%20eq%20guid'4d8e5653-754b-e211-b94e-001b21ce410d')))%20and%20(PurchaseOrderLine/PurchaseOrder/Addresses/any(n:%20((n/AddressType%20eq%20'EndUser')%20or%20(n/AddressType%20eq%20'FreightForwarder')))))


{
"odata.error":{
"code":"","message":{
"lang":"en-US","value":"An error has occurred."
},"innererror":{
"message":"Instance property 'AddressType' is not defined for type 'Amtech.Servtrac.Server.Entities.Security.User'","type":"System.ArgumentException","stacktrace":" at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__21`1.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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
}
}
}

Commented Issue: Web Api 2-OData same variable name causes type error [1128]

$
0
0
I have an odata url that is using the same variable name in two separate any clauses which causes the api to think to that the second variable (i.e. Address entity) is of the same name is of the same type as the first variable (i.e. User) and causes an error for a column not existing. I am using the web api version 2 July 8th build.

http://localhost:2351/ServtracWebPortals/Mexico/amtechcs/servtracweb/dataservice/InvoiceLines?$filter=((Invoice/Customer/Users/any(n:%20(n/Id%20eq%20guid'4d8e5653-754b-e211-b94e-001b21ce410d')))%20and%20(PurchaseOrderLine/PurchaseOrder/Addresses/any(n:%20((n/AddressType%20eq%20'EndUser')%20or%20(n/AddressType%20eq%20'FreightForwarder')))))


{
"odata.error":{
"code":"","message":{
"lang":"en-US","value":"An error has occurred."
},"innererror":{
"message":"Instance property 'AddressType' is not defined for type 'Amtech.Servtrac.Server.Entities.Security.User'","type":"System.ArgumentException","stacktrace":" at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Tracing.Tracers.HttpControllerTracer.<ExecuteAsyncCore>d__5.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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__21`1.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.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
}
}
}
Comments: This appears to be a bug in the Web API OData query processing. For now as a workaround we recommend using different variable names in each part of the query.

Edited Issue: consider how nulls are represented with IEdmObject. [1014]

$
0
0
IEdmObject right now tracks entity instances only which are not nullable. Once, we add support for IEdmObject with complex types and collections, we have to figure out a way to represent null values as IEdmObjects. One strategy could be to have EdmNullValue that implements IEdmObject.

Commented Issue: consider how nulls are represented with IEdmObject. [1014]

$
0
0
IEdmObject right now tracks entity instances only which are not nullable. Once, we add support for IEdmObject with complex types and collections, we have to figure out a way to represent null values as IEdmObjects. One strategy could be to have EdmNullValue that implements IEdmObject.
Comments: Please resolve this when the untyped support is checked in.

Edited Issue: $expand fails when the navigation property being expanded is null. [1043]

$
0
0
**Url**

`/api/passos?$expand=ProximoPasso&$select=Nome,ProximoPasso/Nome`

**Code**

```
public abstract class EntityNome : IEntity
{
public int Id { get; set; }
public string Nome { get; set; }
}
```

```
public class Passo : EntityNome, IAuditavel
{
public virtual Passo ProximoPasso { get; set; }
public virtual ICollection<Usuario> Responsaveis { get; set; }
public virtual ICollection<CheckListItemTemplate> CheckListItens { get; set; }
...
```

**Error**

```
{
"odata.error": {
"code": "",
"message": {
"lang": "en-US",
"value": "An error has occurred."
},
"innererror": {
"message": "Exception has been thrown by the target of an invocation.",
"type": "System.Reflection.TargetInvocationException",
"stacktrace": " at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__a.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.<SendAsync>d__0.MoveNext()",
"internalexception": {
"message": "The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.",
"type": "System.InvalidOperationException",
"stacktrace": " at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)\r\n at lambda_method(Closure , Shaper )\r\n at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)\r\n at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()\r\n at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n at System.Web.Http.OData.Query.ODataQueryOptions.LimitResults[T](IQueryable`1 queryable, Int32 limit, Boolean& resultsLimited)"
}
}
}
}
```

Edited Issue: OData $batch fails with WCF DS client [1135]

$
0
0
with exception,

Unhandled Exception: System.Data.Services.Client.DataServiceRequestException: An
error occurred while processing this request. ---> System.Data.Services.Client.
DataServiceClientException: <Error><Message>No HTTP resource was found that matc
hes the request URI 'http://localhost:8080/http://localhost:8080/Customers(42)/O
rders'.</Message><MessageDetail>No route data was found for this request.</Messa
geDetail></Error>


I think the problem is in the content-id to uri translation.

Edited Issue: metadata uri (json light) is missing $select clause [1107]

$
0
0
Spec here on the metadata url - http://docs.oasis-open.org/odata/odata/v4.0/csprd01/part1-protocol/odata-v4.0-csprd01-part1-protocol.html#_Toc355089421

Issue:
GET ~/Customers?$select=Name

Expected:

```
{
"odata.metadata":"http://localhost/$metadata#Customers&$select=Name","value":[
{
"Name":"Raghu"
}
]
}
```

Actual:

```
{
"odata.metadata":"http://localhost/$metadata#Customers","value":[
{
"Name":"Raghu"
}
]
}
```
The metadata URL describes the content of the payload and is really important in json light.

Edited Feature: Add simple support for OData nested paging [1101]

$
0
0
Implement nested paging where every level is paged at the same size.

Edited Issue: NullPropagation option smart detection should handle ObjectContext and ObjectQuery [995]

$
0
0
We try to figure out whether we should do null propagation in query composition by looking at the QueryProvider of the IQueryable. We handle Linq2Objects, Linq2Sql and EntityFramework there.

For EntityFramework, we are only handling DbContext and DbSets. We should handle ObjectContext and ObjectQuery as well there.

Edited Issue: Returning related entities when they are null. OData Web API [1134]

$
0
0
If I try to load a related entity which is null, for instance I have my schema as Carrier has many Phones and I retrieved a Phone and I want to load the Carrier but the Carrier is null (which is ok), then I go to my Container and do "LoadProperty(Phone, "Carrier")" I get an exception because on my Web API OData I have GetCarrier in my PhonesController and when it tries to return the Carrier from this Phone which is null it throws the following error:

```
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata=minimalmetadata; streaming=true; charset=utf-8'.
```

With an inner exception of:

```
Cannot serialize a null 'entry'.
```

And a stack trace:

```
at System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteObject(Object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.<>c__DisplayClassa.<WriteToStreamAsync>b__9()
at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
--- 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.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__33.MoveNext()

```
Is this by design or should I be handling this differently?

My controller has the following method:

```
public Carrier GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

return phone.Carrier;
}
```

Or should I change my code to the following:

```
public HttpResponseMessage GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

if(phone.Carrier == null)
return Request.CreateResponse(HttpStatusCode.OK);

return Request.CreateResponse(HttpStatusCode.OK, phone.Carrier);
}
```

By doing this I won't get the error anymore when trying to user LoadProperty even if the related entity is null. Is this the correct way of doing this?

Viewing all 7215 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>