簡體   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