Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a status code, status description and text together in MVC3?

From my MVC3 controller action I want to return HTTP 403, set "status description" to some specific string and also return that string in the result content so that it is visible in the browser.

I can return ContentResult to specify content, but not a status code (such as 403) and not a status description. I can use HttpStatusCodeResult to specify a status code and status description but not the result content.

How do I craft an action result that contains all three?

like image 247
sharptooth Avatar asked Jun 26 '13 15:06

sharptooth


2 Answers

Commonly you would see this done by setting the response code then returning a regular ActionResult

public ActionResult Foo() 
{ 
    Response.StatusCode = 403;
    Response.StatusDescription = "Some custom message";

    return View(); // or Content(), Json(), etc
}

If you really need this to be an ActionResult, you create your own.

Example:

public class HttpStatusContentResult : ActionResult
{
    private string _content;
    private HttpStatusCode _statusCode;
    private string _statusDescription;

    public HttpStatusContentResult(string content, 
                                   HttpStatusCode statusCode = HttpStatusCode.OK,
                                   string statusDescription = null)
    {
        _content = content;
        _statusCode = statusCode;
        _statusDescription = statusDescription;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.StatusCode = (int) _statusCode;
        if (_statusDescription != null)
        {
            response.StatusDescription = _statusDescription;
        }

        if (_content != null)
        {
            context.HttpContext.Response.Write(_content);
        }
    }
}
like image 170
drch Avatar answered Oct 10 '22 08:10

drch


If this is not too dirty

Response.Clear();
Response.Write("Some specific string");
return new HttpStatusCodeResult(403, "another specific string");
like image 38
Andrei Avatar answered Oct 10 '22 09:10

Andrei