繁体   English   中英

自定义InputFormatter在ASP.NET Core 2.0中被忽略

[英]Custom InputFormatter is getting ignored in ASP.NET Core 2.0

我需要构建一个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类。 控制器:

[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应用程序控制器)

我正在使用Postman应用程序进行POST。 没有任何POST会命中SoapInputFormatter

有小费吗? 有任何想法吗?

遇到相同的问题,然后找到此链接:

http://www.dotnetcurry.com/aspnet-mvc/1368/aspnet-core-mvc-custom-model-binding

基本上可以归结为文章中的这些内容:

  • 默认情况下,不是每个绑定源都被选中。 某些模型联编程序要求您专门启用绑定源。 例如,从主体绑定时,需要将[FromBody]添加到模型/动作参数,否则将不使用BodyModelBinder。
  • 特别是,标题,正文和文件绑定源必须由用户专门启用,并将使用特定的模型绑定器

我在POST请求上添加了[FromBody],然后调用了我的自定义InputFormatter。

-里克

我有点晚了,但是您需要使用[ApiController]才能使用InputFormatter。

根据要求编辑:

[ApiController]
[Route("api/[controller]")]
public class ValuesController : Controller
{
  // GET api/values
  [HttpGet]
  public IEnumerable<string> Get()
  {
      return new string[] { "value1", "value2" };
  }
}
....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM