.net core 接收xml、text/plain格式参数

1、接收xml

controller中写法如下

[HttpPost, ActionName("Sign_off")] 
[Produces("application/xml")]//接收
[Consumes("application/xml")]//返回
public async Task Sign_off([FromBody] XmlDocument xmldoc){ .....//你的业务逻辑 } 

Startup.cs中的ConfigureServices加上这一段

services.AddMvc().AddXmlSerializerFormatters();

2.接收text/plain

controller中写法如下

[HttpPost, ActionName("Sign_off")] 
[Produces("text/plain")]//接收
[Consumes("application/json")]//返回
public async Task Sign_off([FromBody] string xmlString){ .....//你的业务逻辑 } 

Startup.cs中的ConfigureServices加上这一段

services.AddMvc(options =>
{
options.InputFormatters.Insert(0, new TextInputFormatter());//接收text/plain
});

注:TextInputFormatter是自定义的,如下

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;

public class TextInputFormatter : InputFormatter
{
    public TextInputFormatter()
    {
        SupportedMediaTypes.Add("text/plain");
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        var request = context.HttpContext.Request;
        using (var reader = new StreamReader(request.Body, Encoding.UTF8))
        {
            var content = await reader.ReadToEndAsync();
            return await InputFormatterResult.SuccessAsync(content);
        }
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }
}

 

posted @ 2023-10-09 14:03  艺洁  阅读(512)  评论(0编辑  收藏  举报