[英]Is this a safe way to get body of a HttpContext request
public static class HttpRequestHelper
{
public static string RequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
}
I plan to call this from ActionFilters to log incoming requests. 我计划从ActionFilters调用它来记录传入的请求。 Of course there could be multiple simultaneous requests.
当然可以有多个同时请求。
Is this approach ok? 这种方法行吗?
Is your question from the perspective of concurrency or ASP.NET Web API in general? 您的问题是从并发性还是ASP.NET Web API的角度而言? Every request has its own context and you are okay with multiple requests going on in parallel.
每个请求都有其自己的上下文,并且可以并行处理多个请求。 But here are two things for you to look at.
但是,有两件事需要您注意。
(1) Since you are using HttpContext
, you are locking yourself to web hosting (IIS), which in many cases should be okay. (1)由于您使用的是
HttpContext
,因此您将自己锁定到Web托管(IIS),在许多情况下应该可以。 But I would like you to be aware of this. 但是,我希望您对此有所了解。
(2) Your code HttpRequestHelper.RequestBody()
will work when called from an action filter, as you mentioned. (2)如前所述,从动作过滤器中调用代码
HttpRequestHelper.RequestBody()
。 However, if you try to call this from other places, say a message handler, this will not work. 但是,如果您尝试从其他地方调用此消息,例如说一个消息处理程序,那么它将无法正常工作。 When I say this will not work, parameter binding that binds request body to action method parameter will not work.
当我说这行不通时,将请求主体绑定到操作方法参数的参数绑定将行不通。 You will need to seek to the beginning once you are done.
完成后,您将需要从头开始。 The reason it works from action filter is that binding would have already happened by the time action filter runs in the pipeline.
它在动作过滤器中起作用的原因是,在动作过滤器在管道中运行时,绑定已经发生。 This is another thing you might need to be aware of.
这是您可能需要注意的另一件事。
I've needed use InputStream of Http Request. 我需要使用Http Request的InputStream。 I have a WebApp and IOS App that navigates to a aspx page, if the url request contains some parameters i read the information in database and if i not find any parameters in url request i read the request body and i work fine !
我有一个WebApp和IOS App,可以导航到aspx页面,如果url请求包含一些参数,则我读取数据库中的信息;如果我在url请求中找不到任何参数,则我读取了请求正文,并且工作正常!
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(Request.QueryString["AdHoc"]) == false)
{
string v_AdHocParam = Request.QueryString["AdHoc"];
string [] v_ListParam = v_AdHocParam.Split(new char[] {','});
if (v_ListParam.Length < 2)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(WS_DemandeIntervention));
WS_DemandeIntervention response = (WS_DemandeIntervention)jsonSerializer.ReadObject(Request.InputStream);
....
}
if (string.IsNullOrEmpty(Request.QueryString["IdBonDeCommande"])==false)
{
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.