看
using System.Xml.Serialization; using Microsoft.AspNetCore.Mvc; using XCGWebApp.Dtos; using XCGWebApp.Common; using System.Text; namespace XCGWebApp.Controllers { [ApiController] [Route("[controller]/[action]")] public class ReqController : ControllerBase { /// <summary> /// 接收字符串或者xml /// </summary> /// <returns></returns> [HttpPost] public JsonResult AcceptXMLOrString() { var len = Convert.ToInt32(HttpContext.Request.ContentLength); byte[] byt = new byte[len]; var ri = HttpContext.Request.BodyReader.AsStream().Read(byt, 0, len); string str = Encoding.UTF8.GetString(byt, 0, len); //如果傳的是xml字符串,反序列化成對象。 ReqDto? dto = null; XmlSerializer serializer = new XmlSerializer(typeof(ReqDto)); using (StringReader sr = new StringReader(str)) { object? obj = serializer.Deserialize(sr); if (obj != null) { dto = (ReqDto)obj; } } ApiResult<object> result = new ApiResult<object>() { errorCode = "0", message = "success", data = dto }; return new JsonResult(result); } /// <summary> /// /Req/SendXML /// </summary> /// <returns></returns> [HttpPost] public async Task<JsonResult> SendXML() { ApiResult<string> result = new ApiResult<string>() { errorCode = "0", message = "success", data = "" }; string xmlStr = ""; var dto = new ReqDto() { ErrorCode = 200, ReqName = "test" }; XmlSerializer serializer = new XmlSerializer(typeof(ReqDto)); using (StringWriter textWriter = new StringWriter()) { serializer.Serialize(textWriter, dto); xmlStr = textWriter.ToString(); } string url = "http://localhost:32831/Req/AcceptXMLOrString"; var res = await ReqUtil.SendRequestXML(url, HttpMethod.Post, xmlStr); result.data = res.ToString(); return new JsonResult(result); } } }