[英]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
基本上可以歸結為文章中的這些內容:
我在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.