2 回答

TA贡献1817条经验 获得超6个赞
请求正文表明嵌入式软件正在发布多部分数据。以下content-disposition意味着它正在发送一个文件details.xml:
------------------------------3cbec9ce8f05
Content-Disposition: form-data; name="ServerData"; filename="details.xml"
Content-Type: text/plain
所以你不需要手动删除 '-----------------------------3cbec9ce8f05' 和Content-Type=.... 只需使用Request.Form.Files.
此外,正如@ivan-valadares所建议的,您可以使用模型活页夹来提升重物。但似乎他将所有请求正文视为字符串,然后构造一个XDocument. 一种更优雅的方式是用于XmlSerializer创建强类型对象。此外,IModelBinder 接口没有public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext). 我们应该BindModelAsync(ModelBindingContext bindingContext)改用。
所以创建一个模型活页夹如下:
public class EmbededServerDataBinder<T> : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); }
var modelName = bindingContext.BinderModelName ?? "ServerData";
XmlSerializer serializer = new XmlSerializer(typeof(T));
var data= bindingContext.HttpContext.Request.Form.Files[modelName];
if(data == null){
bindingContext.ModelState.AddModelError(modelName,"invalid error");
return Task.CompletedTask;
}
using(var stream = data.OpenReadStream()){
var o = serializer.Deserialize(stream);
bindingContext.Result = ModelBindingResult.Success(o);
}
return Task.CompletedTask;
}
}
现在您可以在 Action 方法中使用它:
[HttpPost]
public IActionResult Post([ModelBinder(typeof(EmbededServerDataBinder<Ow_ServerModel>))] Ow_ServerModel ServerData)
{
return Ok("Working");
}
注意事项的名称ServerData。模型绑定器将在 content-disposition 中查找此名称。
我用你的有效载荷测试它,它按预期工作:

TA贡献1818条经验 获得超7个赞
您正在尝试使用 ActionFilter 来做到这一点,我建议使用自定义 Binder 并使用正则表达式从请求中提取 de xml。
在 WebApiConfig.cs 中注册新的自定义 xml 绑定器
public static void Register(HttpConfiguration config)
{
config.Services.Insert(typeof(ModelBinderProvider), 0,
new SimpleModelBinderProvider(typeof(XDocument), new XmlCustomBinder()));
}
创建一个自定义活页夹,它将获取内容主体并仅提取 xml
public class XmlCustomBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
try
{
var parsedXml = actionContext.Request.Content.ReadAsStringAsync().Result;
Regex regex = new Regex(@"<\?xml.*>", RegexOptions.Singleline);
Match match = regex.Match(parsedXml);
if (!match.Success) return false;
parsedXml = match.Groups[0].Value;
TextReader textReader = new StringReader(parsedXml);
XDocument xDocument = XDocument.Load(textReader);
bindingContext.Model = xDocument;
return true;
}
catch(Exception ex)
{
bindingContext.ModelState.AddModelError("XmlCustomBinder", ex);
return false;
}
}
}
控制器代码,获取 XDocument (XML) 值
[HttpPost]
[OwServer]
public IActionResult Post([ModelBinder(typeof(XmlCustomBinder))] XDocument xDocument)
{
return Ok("Working");
}
https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument?view=netframework-4.7.2
- 2 回答
- 0 关注
- 147 浏览
添加回答
举报