Domanda

MVC controller has many object which exists in HttpContext subobject too. What are differences between this objects?

        var res = HttpContext.Response;
        var res1 = Response;

        var req = HttpContext.Request;
        var req1 = Request;
È stato utile?

Soluzione

The Request and Response properties of the Controller class are really just returning HttpContext.Request and HttpContext.Response. There is no difference in the two. The presence of the Controller properties is really for succinctness to avoid using HttpContext.Request / HttpContext.Result.

You can see it in the source code:

public abstract class Controller 
{
    // ...

    public HttpRequestBase Request
    {
        get { return HttpContext == null ? null : HttpContext.Request; }
    }

    public HttpResponseBase Response
    {
        get { return HttpContext == null ? null : HttpContext.Response; }
    }

    // ...

}

You should, however, use the Controller properties as they are directly related to MVC and not the System.Web.dll stack. If, in the future, there is a change in the MVC framework in regards to the Request / Response object model in such a way that the dependency with the System.Web and HttpContext class is removed, the Request and Response of the Controller itself should reflect directly what is is, and will require less change in code of your part (even though I think it's unlikely we see this kind of breaking change in the near future).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top