爲了在MVC中傳遞數據,必須創建自己的媒體類型格式化程序來處理純文本。然後將格式化程序添加到配置部分。
要使用新格式化程序,請指定該格式化程序的Content-Type,如 text/plain。
樣品格式化文本
using System;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.IO;
using System.Text;
namespace SampleMVC.MediaTypeFormatters
{
public class TextMediaTypeFormmatter : XmlMediaTypeFormatter
{
private const int ByteChunk = 1024;
private UTF8Encoding StringEncoder = new UTF8Encoding();
public TextMediaTypeFormmatter()
{
base.UseXmlSerializer = true;
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
public override bool CanReadType(Type type)
{
if (type == typeof(string))
{
return true;
}
return false;
}
public override bool CanWriteType(Type type)
{
if (type == typeof(string))
{
return true;
}
return false;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
{
StringBuilder StringData = new StringBuilder();
byte[] StringBuffer = new byte[ByteChunk];
int BytesRead = 0;
Task<int> BytesReadTask = readStream.ReadAsync(StringBuffer, 0, ByteChunk);
BytesReadTask.Wait();
BytesRead = BytesReadTask.Result;
while (BytesRead != 0)
{
StringData.Append(StringEncoder.GetString(StringBuffer, 0, BytesRead));
BytesReadTask = readStream.ReadAsync(StringBuffer, 0, ByteChunk);
BytesReadTask.Wait();
BytesRead = BytesReadTask.Result;
}
return Task<object>.Run(() => BuilderToString(StringData));
}
private object BuilderToString(StringBuilder StringData)
{
return StringData.ToString();
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
byte[] StringBuffer = StringEncoder.GetBytes((string)value);
return writeStream.WriteAsync(StringBuffer, 0, StringBuffer.Length);
}
}
}
控制器的方法:
config.Formatters.Add(new TextMediaTypeFormmatter());
提琴手標題:
User-Agent: Fiddler
Content-Type: text/plain
在WebApiConfig.cs註冊方法
[HttpPost]
public async Task<HttpResponseMessage> UsingString([FromBody]string XmlAsString)
{
if (XmlAsString == null)
{
return this.Request.CreateResponse(HttpStatusCode.BadRequest);
}
return this.Request.CreateResponse(HttpStatusCode.OK, new { });
}
設置
當您嘗試在正文中發送XML時,您將Content-Type標頭設置爲什麼內容?如果您更新了問題以顯示您發送的Composer選項卡中的所有內容,可能會有所幫助。 – EricLaw
找到了答案,我需要一種方法來在關鍵字/值對中粘貼一段XML,並使用ActionFilter似乎起作用。現在,我只需要弄清楚如何解析經典ASP中的XML。 – punkouter