Search code examples
visual-studioload-testingweb-testing

How do I read, update and replace a "String body" field in a web test from a plugin?


My recorded web performance test has several "String body" fields and I need to modify their contents at run time from within a web test request plugin.

The "String body" field is not directly available from the various fields and subfields of the PreRequestEventArgs.

How do I read out the "String body" field into a string and, after modifying it, write it back?


Solution

  • To read out the "String body" field, cast the request body to a StringHttpBody which makes the string available. To write it back, create a new StringHttpBody object to contain the updated string, then write it into the request.

    Using a plugin I need to modify the "String body" field of a request in a web performance test. I can access the contents using the following code:

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        if ( e.Request.Body == null ) { return; }
        StringHttpBody httpBody = e.Request.Body as StringHttpBody;
        if ( httpBody == null ) { return; }
        string body = httpBody.BodyString;
    
        string updatedBody = UpdateBody(body);
    
        StringHttpBody newBody = new StringHttpBody();
        newBody.BodyString = updatedBody;
        e.Request.Body = newBody;
    }