我需要构建一个 ASP.NET Core 2.0 Web API 应用程序,它将能够完成自定义 XML 输入和输出格式设置。
我在设置自定义输出格式化程序方面取得了成功,但没有成功设置自定义输入格式化程序。
更准确地说,这是启动配置:
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc(opt =>
{
opt.ReturnHttpNotAcceptable = true;
opt.OutputFormatters.Clear();
opt.InputFormatters.Clear();
opt.InputFormatters.Add(new SoapInputFormatter());
opt.OutputFormatters.Add(new SoapOutputFormatter());
});
}
想法是拥有自定义 SOAP 输入和输出格式。不,现有的 XmlDataContractSerializerInputFormatter
不起作用。
SoapOutputFormatter
类:
public class SoapOutputFormatter : IOutputFormatter
{
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
return true;
}
public async Task WriteAsync(OutputFormatterWriteContext context)
{
var bytes = Encoding.UTF8.GetBytes(context.Object.ToString());
await context.HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
}
}
和 SoapInputFormatter
类:
public class SoapInputFormatter : InputFormatter
{
public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
throw new NotImplementedException();
}
protected override bool CanReadType(Type type)
{
return true;
}
}
我设置断点只是为了让代码被调用,以便稍后我可以实际实现有用的代码。但是 SoapInputFormatter
类根本没有被调用。 Controller :
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
(经典的新 web api 应用程序 Controller )
我正在使用 Postman
应用程序进行 POST。没有 POST 会命中 SoapInputFormatter
。
有什么建议吗?有什么想法吗?
最佳答案
有同样的问题然后找到这个链接:
http://www.dotnetcurry.com/aspnet-mvc/1368/aspnet-core-mvc-custom-model-binding
基本上归结为文章中的这些项目:
- 默认情况下并非每个绑定(bind)源都被选中。某些模型绑定(bind)器要求您专门启用绑定(bind)源。例如,从 Body 绑定(bind)时,您需要将 [FromBody] 添加到您的模型/ Action 参数中,否则将不会使用 BodyModelBinder。
- 特别是,Headers、Body 和 Files 绑定(bind)源必须由用户专门启用,并将使用特定的模型绑定(bind)器
我在 POST 请求上添加了 [FromBody],然后调用了我的自定义 InputFormatter。
-瑞克
关于c# - 自定义 InputFormatter 在 ASP.NET Core 2.0 中被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47025515/