Khi code WCF Rest mà client submit POST request với dạng application/x-www-form-urlencoded thì code như sau:
Khai báo input đầu vào là kiểu Stream. Sau đó read string ra 1 biến vì khi POST dạng application/x-www-form-urlencoded thì các tham số request sẽ được format kiểu key1=value1&key2=value2
Do đó chỉ cần read ra 1 chuỗi string, sau đó bóc tách từng cặp key value để xử lý.
Nguồn: https://social.msdn.microsoft.com/Forums/vstudio/en-US/2a1b5690-fb2c-4303-a122-fe99d383be7c/how-to-accept-applicationxwwwformurlencoded?forum=wcf
public Stream ProcessArbitraryInput(Stream input)
{
string strInput = new StreamReader(input).ReadToEnd();
string htmlResult = @"<html><head><title>Result</title></head>
<body>
<h1>First: {{first}}</h1>
<h1>Second: {{second}}</h1>
</body></html>";
Regex inputRegex = new Regex(@"First=([^\&]+)\&Second=(.+)");
Match match = inputRegex.Match(strInput);
string first, second;
if (match.Success)
{
first = match.Groups[1].Value.Replace('+', ' ');
second = match.Groups[2].Value.Replace('+', ' ');
}
else
{
first = second = "Error";
}
htmlResult = htmlResult.Replace("{{first}}", first).Replace("{{second}}", second);
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
return new MemoryStream(Encoding.UTF8.GetBytes(htmlResult));
}
No comments:
Post a Comment