为了在 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);
}
}
}
控制器方法:
[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 { });
}
WebApiConfig.cs 注册方法中的设置:
config.Formatters.Add(new TextMediaTypeFormmatter());
提琴手头:
User-Agent: Fiddler
Content-Type: text/plain