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 關注
- 146 瀏覽
添加回答
舉報