Reputation: 52311
In ASP.NET MVC, Controller
class has only a limited set of methods to use to return something from an action.
There is a HttpNotFoundResult HttpNotFound()
method, but no other methods for errors.
What's really inside HttpNotFound()
? How to write a similar method for other error codes, like 401 Unauthorized
or 403 Forbidden
or 406 Not Acceptable
?
Upvotes: 0
Views: 1268
Reputation: 236208
It is implemented this way:
public class HttpNotFoundResult : HttpStatusCodeResult
{
public HttpNotFoundResult() : this(null)
{
}
public HttpNotFoundResult(string statusDescription) :
base(HttpStatusCode.NotFound, statusDescription)
{
}
}
When executed, HttpStatusCodeResult simply sets status code and status description to context.HttpContext.Response
. You can inherit from HttpStatusCodeResult class and create your own results. E.g.
public class HttpUnauthorizedResult : HttpStatusCodeResult
{
public HttpUnauthorizedResult() : this(null)
{
}
public HttpUnauthorizedResult(string statusDescription) :
base(HttpStatusCode.Unauthorized, statusDescription)
{
}
}
Upvotes: 2