开发者

How to log POSTed forms submissions?

Back in the ASP classic days when i needed to write out the name/value pairs of forms submitted by POST i thru this loop into the page:

on error resume next
for each x in Request.Form
 Response.AppendToLog x & "=" &  Request(x)
next
开发者_如何学Python

It threw all the form fields and values into the log just as GETs are. Does IIS7 .net give me any better method? (this is for the dev/testing portion of the project i don't have any concern about the space or cycles used to accomplish this).

thx


You can create an http module to log all posts. It allows you to log outside of the pages, a single point of logging instead of having to add the logic to all pages where you want to log activity.

Here you have some of the code. You would have to avoid logging viewstate since is tons of useless information. So you have to add some logic to achieve this.

public class ActivityLogModule: IHttpModule
{
    public void Init(HttpApplication application)
    {
        application.EndRequest += (new EventHandler(this.Application_EndRequest));
    }

    private void Application_EndRequest(Object source, EventArgs e)
    {
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;

        if (RecordActivity(context))
        {
            ActivityLogger.Instance.Log(application.Context.User.Identity.Name, 
                 application.Context.Request.Url.AbsoluteUri, 
                 application.Context.Request.Form.ToString());
        }
    }

    public void Dispose(){}

    protected bool RecordActivity(HttpContext context)
    {
        if (!context.Request.RequestType.Equals("POST"))
        {
            return false;
        }

        return true;
    }
}


You could have something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
       LogPostValues();
}

private void LogPostValues()
{
    string logPath = @"C:\PostedValuesLog.txt";

    StringBuilder sb = new StringBuilder();

    sb.AppendFormat("Logging: {0}", Request.Path);

    sb.Append("Form Values");
    foreach (string key in Request.Form)
    {
            string val = Request.Form[key];
            sb.AppendFormat("{0} = {1}<br/>", key, val);
    }

    sb.Append(Environment.NewLine);
    sb.Append("QueryString Values");

    foreach (string key in Request.QueryString)
    {
            string val = Request.QueryString[key];
            sb.AppendFormat("{0} = {1}<br/>", key, val);
    }

    sb.Append(Environment.NewLine);
    sb.Append(Environment.NewLine);
    sb.Append(Environment.NewLine);

    File.AppendAllText(logPath, sb.ToString());
}

This is a crude method though and shouldn't really be used in production code. However, as this is just for development & testing, it should suffice to track what data is being posted to your page via the querystring and form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜