我有一个与自定义格式化程序相关的非常愚蠢的问题。
public class RequestHeaderJsonFormatter : MediaTypeFormatter
{
public RequestHeaderJsonFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return base.ReadFromStreamAsync(type, readStream, content, formatterLogger);
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
}
我在Global.asax中注册格式化程序,如下所示:
protected void Application_Start() { GlobalConfiguration.Configuration.Formatters.Insert(0,new RequestHeaderJsonFormatter());
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
我的问题是在执行控制器操作时永远不会调用ReadFromStreamAsync。
public class HomeController : ApiController
{
public HttpResponseMessage GetString(string param)
{
var response = Request.CreateResponse(HttpStatusCode.OK, "ererrer");
return response;
}
}
我做错了什么......我无法理解。任何帮助将不胜感激。
答案 0 :(得分:0)
默认情况下,'string'类型的动作参数应该从Uri读取,除非使用[FromBody]属性来装饰它,在这种情况下格式化器会出现。
public HttpResponseMessage GetString(* [FromBody] * string param)