C# ASP.NET Framework Web Api 模式下 body 参数传递,post 参数方式

Visual Studio 2019 + .NET Framework 4.7.2


1WebApiController

public class ValuesController : ApiController

{

    [HttpPost]

    public UserModel GetUser(UserModel userModel)

    {

        return new UserModel

        {

            UserId = userModel.UserId,

            UserName = userModel.UserName,

        };

    }

    public class UserModel

    {

        public int UserId { get; set; }

        public string UserName { get; set; }

    }

}


POST 支持 json 参数


POST 支持 form 表单参数


GET 请求

public class ValuesController : ApiController

{

    [HttpGet]

    public HttpResponseMessage GetUser(string user)

    {

        return new HttpResponseMessage

        {

            Content = new StringContent("{\"user\": \"" + user + "\"}", System.Text.Encoding.UTF8, "application/json"),

            StatusCode = HttpStatusCode.OK

        };

    }

}



GET 多参数请求

public class ValuesController : ApiController

{

    [HttpGet]

    public HttpResponseMessage GetUser(int id, string name)

    {

        return new HttpResponseMessage

        {

            Content = new StringContent("{\"id\": " + id + " ,\"name\": \"" + name + "\"}", System.Text.Encoding.UTF8, "application/json"),

            StatusCode = HttpStatusCode.OK

        };

    }

}



2MvcController

public class ValuesController : Controller

{

    [HttpPost]

    public ActionResult GetUser(UserModel userModel)

    {

        return new ContentResult()

        {

            Content = JsonConvert.SerializeObject(new UserModel

            {

                UserId = userModel.UserId,

                UserName = userModel.UserName,

            }),

            ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"),

            ContentType = "application/json",

        };

    }

    public class UserModel

    {

        public int UserId { get; set; }

        public string UserName { get; set; }

    }

}


POST 支持 form 表单参数


POST 支持 json 参数


GET 请求

public class ValuesController : Controller

{

    [HttpGet]

    public ActionResult GetUser(string user)

    {

        return new ContentResult()

        {

            Content = "{\"user\": \"" + user + "\"}",

            ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"),

            ContentType = "application/json",

        };

    }

}



GET 多参数请求

public class ValuesController : Controller

{

    [HttpGet]

    public ActionResult GetUser(int id, string name)

    {

        return new ContentResult()

        {

            Content = "{\"id\": " + id + " ,\"name\": \"" + name + "\"}",

            ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"),

            ContentType = "application/json",

        };

    }

}



作者最新文章
C# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角