8

Got a .NET/C# question...

I need to parse some input post data thats in a "multipart/form-data" format to extract the passed username and password. Anyone know how to do this without writing my own parsing code?

Note the input post data looks something like this:

---------1075d313df8d4e1d
Content-Disposition: form-data; name="username"

x@y.com
---------1075d313df8d4e1d
Content-Disposition: form-data; name="password"

somepassword
---------1075d313df8d4e1d--

To demostrate my code looks something like this at the moment:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "Login", BodyStyle = WebMessageBodyStyle.Bare)]
public Stream Login(Stream input)
{
    string username = String.Empty;
    string password = String.Empty;

    StreamReader sr = new StreamReader(input);
    string strInput = sr.ReadToEnd();
    sr.Dispose();

    // Help needed here:
    usermame = ?.Parse(strINput, "username");
    password = ?.Parse(strINput, "password");

    // blah blah blah return login XML response as a Stream
}
yfeldblum
  • 65,165
  • 12
  • 129
  • 169
Oliver Pearmain
  • 19,885
  • 13
  • 86
  • 90
  • See here for a solution that does not require ASP.NET: http://stackoverflow.com/questions/7460088/reading-file-input-from-a-multipart-form-data-post/21689347#21689347 – Ohad Schneider Feb 10 '14 at 22:45

2 Answers2

7

Marc's got it. The easiest way to use the ASP.NET compatibility requirements mode is to apply the AspNetCompatibilityRequirementsMode attribute on your operation. Then you have access to the HttpContext form params. Here's how you'd go about it:

        [OperationContract]
        [WebInvoke(Method = "POST", 
                    UriTemplate = "Login", 
                    BodyStyle = WebMessageBodyStyle.Bare)]
        [AspNetCompatibilityRequirements(RequirementsMode = 
                    AspNetCompatibilityRequirementsMode.Required)]
        public Stream Login(Stream input)
        {
            string username = HttpContext.Current.Request.Params["username"];
            string password = HttpContext.Current.Request.Params["password"];
        }
Mike Atlas
  • 8,193
  • 4
  • 46
  • 62
  • 1
    Thank you for your reply. I did manage to get AspNetCompatibility mode working so this is a feasible solution. However this wouldn't work with my unit tests as I spin up an instance of my service in code and you can't set the AspNetCompatibility mode in code (as far as I know), see here: http://stackoverflow.com/questions/1721219 So in the end I've just written a custom parser using RegEx. Not what I originally wanted to do as its not the most elegent solution but it gets the job done. – Oliver Pearmain Nov 13 '09 at 11:53
2

Could you not post to a regular ASP.NET page (perhaps an ashx/handler, or MVC) and just use Request.Form? This supports multi-part.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900