Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing "multipart/form-data" in .NET/C#

Tags:

html

c#

.net

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"

[email protected]
---------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
}
like image 657
Oliver Pearmain Avatar asked Nov 11 '09 17:11

Oliver Pearmain


2 Answers

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"];
        }
like image 179
Mike Atlas Avatar answered Oct 06 '22 12:10

Mike Atlas


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.

like image 2
Marc Gravell Avatar answered Oct 06 '22 12:10

Marc Gravell