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?
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") });
}
In the the first situation, you are still going to be returning the object in the Content
method, eg:
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, eg:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.