Visual Studio 2019 + .NET Framework 4.7.2
1、WebApiController
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
};
}
}
2、MvcController
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",
};
}
}