post請求,body傳值支援text/plain
阿新 • • 發佈:2020-07-31
今天寫了一個介面,需要接收body中的純文字,但是純文字不能是json型別,需要是支援text/plain型別的,所以就去搜了一下,後面才知道,需要重新寫一個方法。
第一種方法:
public class RawRequestBodyFormatter : IInputFormatter { public RawRequestBodyFormatter() { } public bool CanRead(InputFormatterContext context) { if (context == null) throw new ArgumentNullException("argument is Null"); var contentType = context.HttpContext.Request.ContentType; if (string.IsNullOrEmpty(contentType) || contentType == "text/plain" || contentType == "application/octet-stream") return true; return false; } public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context) { var request = context.HttpContext.Request; var contentType = context.HttpContext.Request.ContentType; if (string.IsNullOrEmpty(contentType) || contentType.ToLower() == "text/plain") { using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8)) { var content = await reader.ReadToEndAsync(); return await InputFormatterResult.SuccessAsync(content); } } if (contentType == "application/octet-stream") { using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8)) { using (var ms = new MemoryStream(2048)) { await request.Body.CopyToAsync(ms); var content = ms.ToArray(); return await InputFormatterResult.SuccessAsync(content); } } } return await InputFormatterResult.FailureAsync(); } }
第二種方法:
public sealed class PlainTextInputFormatter : TextInputFormatter { public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) { string content; using(var reader = context.ReaderFactory(context.HttpContext.Request.Body, encoding)) { content = await reader.ReadToEndAsync(); } // 最後一步別忘了 return await InputFormatterResult.SuccessAsync(content); } }
public sealed class CustInputFormatter : InputFormatter { public CustInputFormatter() { SupportedMediaTypes.Add("text/plain"); } protected override bool CanReadType(Type type) { return (type == typeof(DateTime)) || (type == typeof(int)); } public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { string val; using (var reader = context.ReaderFactory(context.HttpContext.Request.Body, Encoding.UTF8)) { val = await reader.ReadToEndAsync(); } InputFormatterResult result = null; if(context.ModelType == typeof(DateTime)) { result = InputFormatterResult.Success(DateTime.Parse(val)); } else { result = InputFormatterResult.Success(int.Parse(val)); } return result; } }