gpt4 book ai didi

ajax - 将 XML 发布到 asp.net core 2.0 web api

转载 作者:数据小太阳 更新时间:2023-10-29 01:57:04 24 4
gpt4 key购买 nike

我正在尝试将 XML 发布到 asp.net core 2:

$.ajax({
type: "POST",
url: 'api/Test',
data: "<test>hello<test>",
contentType: "application/xml",
success: function (response) { alert(response); },
});

我应该如何编写操作,以便它接受 xml 作为参数?

  • IActionResult Post([FromBody]string xml) -> xml 为空
  • IActionResult Post([FromBody]XElement xml) -> xml 为空
  • IActionResult Post(XElement xml) ->InvalidOperationException:无法创建“System.Xml.Linq.XElement”类型的实例。模型绑定(bind)的复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数。
  • IActionResult Post(string xml) -> xml 为空

在 Startup.ConfigureServices 中:

services.AddMvc()
.AddXmlSerializerFormatters();

如何编写 Controller 以使其接受 XML 作为参数?我知道我可以从 HttpContext.Request 读取它,但我希望它成为参数

最佳答案

我最终创建了自定义 InputFormatter,这非常简单,但如果有更好的选择,非常欢迎您写下答案!

public class XDocumentInputFormatter : InputFormatter, IInputFormatter, IApiRequestFormatMetadataProvider
{
public XDocumentInputFormatter()
{
SupportedMediaTypes.Add("application/xml");
}

protected override bool CanReadType(Type type)
{
if (type.IsAssignableFrom(typeof(XDocument))) return true;
return base.CanReadType(type);
}

public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var xmlDoc = await XDocument.LoadAsync(context.HttpContext.Request.Body, LoadOptions.None, CancellationToken.None);
return InputFormatterResult.Success(xmlDoc);
}
}

在startup.cs中注册XDocumentInputFormatter

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.InputFormatters.Insert(0, new XDocumentInputFormatter()));
}

关于ajax - 将 XML 发布到 asp.net core 2.0 web api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com