How can I get a reference to an HttpResponse in ASP.NET MVC?

佐手、 提交于 2019-12-03 08:22:12

问题


I'm calling a third-party library that takes a System.Web.HttpResponse. I see I have a HttpResponseBase, but not HttpResponse like in web forms.

Is there a way to get the HttpResponse? Using MVC 3.

[Edit] : I'm trying to do this in a controller method. Also corrected casing.


回答1:


If you need to interact with systems which take the non-mockable types, you can get access to the current HttpContext via the static property System.Web.HttpContext.Current. The HttpResponse is just hanging off of there via the Response property.




回答2:


In mvc application you can use HttpContext.ApplicationInstance.Response.This helped me for getting the HttpResponse in MVC Application.




回答3:


No, but your HttpResponseBase is probably an HttpResponseWrapper which contains an HttpResponse inside of it. All the HttpResponse methods are accessible from the HttpResponseBase.

If you want access to the HttpResponse, then you could add a reference to it in HttpContext.Items in your IHttpHandler or somewhere earlier in the ASP.NET lifecycle. The BeginRequest event would be a good point to do this.

Your HttpContext.Items references the same dictionary that HttpContextBase.Items references, so you will have access to all those items in MVC3

To clarify,

It is an HttpResponseWrapper, but there is no public accessor for the HttpResponse. So, there is not a directly accessible reference. To make a directly accessible reference before the framework decides to start giving you the wrapper instead of the underlying reference, create an event handler for HttpApplication.BeginRequest event. Your handler will have a reference to the HttpContext object. Set HttpContext.Items["HttpRequest"] = HttpContext.Request. Then in your controller you will be able to access the HttpRequest reference by RequestContext.HttpContext.Items["HttpRequest"].



来源:https://stackoverflow.com/questions/5313495/how-can-i-get-a-reference-to-an-httpresponse-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!