admin

来自 C# 客户端的多部分表单

sql

我正在尝试从 C# 客户端(Outlook 插件)填写 php 应用程序中的表单。我使用 Fiddler 从 php 应用程序中查看原始请求,并且表单作为多部分/表单传输。不幸的是,.Net 没有原生支持这种类型的表单(WebClient 只有一种上传文件的方法)。有人知道图书馆或有一些代码来实现这一目标吗?我想发布不同的值,另外(但只是有时)一个文件。


阅读 131

收藏
2021-07-01

共1个答案

admin

这是从我写的一些示例代码中剪切和粘贴的,希望它应该提供基础知识。目前只支持文件数据和表单数据。

public class PostData
{

    private List<PostDataParam> m_Params;

    public List<PostDataParam> Params
    {
        get { return m_Params; }
        set { m_Params = value; }
    }

    public PostData()
    {
        m_Params = new List<PostDataParam>();

        // Add sample param
        m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));
    }


    /// <summary>
    /// Returns the parameters array formatted for multi-part/form data
    /// </summary>
    /// <returns></returns>
    public string GetPostData()
    {
        // Get boundary, default is --AaB03x
        string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();

        StringBuilder sb = new StringBuilder();
        foreach (PostDataParam p in m_Params)
        {
            sb.AppendLine(boundary);

            if (p.Type == PostDataParamType.File)
            {
                sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
                sb.AppendLine("Content-Type: text/plain");
                sb.AppendLine();
                sb.AppendLine(p.Value);                 
            }
            else
            {
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
        }

        sb.AppendLine(boundary);

        return sb.ToString();           
    }
}

public enum PostDataParamType
{
    Field,
    File
}

public class PostDataParam
{


    public PostDataParam(string name, string value, PostDataParamType type)
    {
        Name = name;
        Value = value;
        Type = type;
    }

    public string Name;
    public string FileName;
    public string Value;
    public PostDataParamType Type;
}

要发送数据,您需要:

HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);
oRequest.ContentType = "multipart/form-data";                       
oRequest.Method = "POST";
PostData pData = new PostData();

byte[] buffer = encoding.GetBytes(pData.GetPostData());

// Set content length of our data
oRequest.ContentLength = buffer.Length;

// Dump our buffered postdata to the stream, booyah
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();

// get the response
oResponse = (HttpWebResponse)oRequest.GetResponse();

希望那很清楚,我已经从几个来源剪切和粘贴,以使内容更整洁。

2021-07-01