Reputation: 8357
I am coding a C# WebApi 2
webservice, and I have a question in regards to returning a HttpStatusCode
from an IQueryable<T>
webservice function.
If a web service function returns a single object, the following can easily be used:
public async Task<IHttpActionResult> GetItem(int id)
{
return Content(HttpStatusCode.Unauthorized, "Any object");
}
In the following situation, I am not sure on how to return a specified HttpStatusCode
:
public IQueryable<T> GetItems()
{
return Content(HttpStatusCode.Unauthorized, "Any object");
}
Can I please have some help with this?
Upvotes: 6
Views: 1719
Reputation: 3122
In the the first situation, you are still going to be returning the object in the Content
method, e.g:
public IHttpActionResult GetItem(int id)
{
return Content(HttpStatusCode.Unauthorized, "Any object");
}
When you execute that method, you would see a "Any object"
returned to the client. In Web API 2 IHttpActionResult
is essentially a fancy factory around HttpResponseMessage
. If you ignore that the return type of the method is IHttpActionResult
, you can return an IQueryable
by replacing "Any object" with the queryable, e.g:
public IHttpActionResult GetItem(int id)
{
IQueryable<object> results;
return Ok(results);
}
Some more info on action results in Web API can be found here:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/action-results
Upvotes: 0
Reputation: 35544
You can throw a HttpResponseException
with the appropriate statuscode
public IQueryable<T> GetItems()
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("Any object") });
}
Upvotes: 6