接收参数
Get
第一种,通过参数列表直接获取数据,这里还可以使用FromUri特性修饰,其官方解释为:一个特性,该特性指定操作参数来自传入HttpRequestMessage的URI;
[HttpGet]
public string test(string b) {
return b;
}
[HttpGet]
public string test([FromUri]string b) {
return b;
}
第二种,使用HttpContext.Current.Request,来获取参数的值
[HttpGet]
public string test2() {
string name = HttpContext.Current.Request["name"];
string age = HttpContext.Current.Request["age"];
return $@"姓名:{name},年龄:{age}";
}
Post
get的两种方式,在post这里同样适用,这里不做赘述
这里使用了FromBody和Required
[HttpPost]
public string test3([FromBody]People param)
{
if (!ModelState.IsValid)
{
string error = string.Empty;
foreach (var key in ModelState.Keys)
{
var state = ModelState[key];
if (state.Errors.Any())
{
error += state.Errors.First().ErrorMessage + ",";
}
}
error = error.Trim(',');
return error;
}
return $@"姓名:{param.name},年龄:{param.age}";
}
public class People {
[Required(ErrorMessage = "名称为必填字段")]
public string name { get; set; }
public string age { get; set; }
}
其他特性
路由前缀属性 Route Prefixes
HTTP 方法列表属性 AcceptVerbs
访问路径属性 Route
[RoutePrefix("api")]//默认路由前缀
public class TestController : ApiController
{
//路由和参数约束
[Route("action/{b:int}/{c:int}")]
//post和get请求都可以调用
[AcceptVerbs("POST", "GET","OPTIONS")]
//https://localhost:44353/api/action/25/15
public int test([FromUri]int b, [FromUri]int c) {
return b+c;
}
//用符号“~”覆盖路由前缀
[Route("~/api2/action2")]
[HttpPost]
//https://localhost:44353/api2/action2/
public string test2() {
string name = HttpContext.Current.Request["name"];
string age = HttpContext.Current.Request["age"];
return $@"姓名:{name},年龄:{age}";
}
}
实体类的一些常用特性
//必填校验,放在实体类属性之上
//要求Title不为空。
//使用自定义验证错误。
[Required(ErrorMessage = "来源标识为必填字段")]
public string source { get; set; }
//正则表达式
[RegularExpression(pattern:@"^[1-9]\d*$",ErrorMessage ="请选择部门")]
//检测值是否相等
[Compare("NewPassword",ErrorMessage ="确认密码和新密码不一致,请检查")]
//校验长度
[MaxLength(length:11,ErrorMessage ="长度不超过11")]
[MinLength(length:11,ErrorMessage ="长度至少11")]
//简易正则
Range[0,100,ErrorMessage="请输入0到100的数字"]
构造函数包含3种
RangeAttribute(int32,int32)
RangeAttribute(double,double)
RangeAttribute(Type,string,string)
//反序列化忽略
若要忽略单个属性,请使用 [JsonIgnore] 特性
//主要是用来执行自定义的验证
CustomValidation
构造方法的参数如下
Type validatorType :自定义验证方法的类
string method:自定义验证的方法名称
//这个类让我们自定义格式检验注解变得简单
//先定义检测方法
public class TestValidator
{
public static ValidationResult TestAge(int age)
{
if (age > 10 && age < 20)
{
return new ValidationResult("10<age<20,你太年轻了");
}
else
{
return ValidationResult.Success;
}
}
}
//然后应用注解
[CustomValidation(typeof(TestValidator),"TestAge")]
public int Age { get; set; }
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//controller中添加以下代码,以返回错误信息
if (!ModelState.IsValid)
{
string error = string.Empty;
foreach (var key in ModelState.Keys)
{
var state = ModelState[key];
if (state.Errors.Any())
{
error += state.Errors.First().ErrorMessage+",";
}
}
error = error.Trim(',');
return error;
}
前端调用
这里都已test为例;
one
//_self表示不会打开一个新的窗体
window.open("https://localhost:44353/Test/test?b=123","_self")
two
fetch("https://localhost:44353/Test/test?b=123").then(data=>{return data.text()}).then(result=>{console.log(result)})
three
var httpRequest = new XMLHttpRequest();
httpRequest.open("get", "https://localhost:44353/Test/test?b=123", true);
httpRequest.send()
httpRequest.responseText
four
ajax、axios、alova 这里就不举例了
后端调用接口
HttpWebRequest 这里我就不写了
HttpClient
static async Task Main(string[] args)
{
HttpClient httpClient = new HttpClient();
var rep = await httpClient.GetAsync("https://localhost:44353/Test/test?b=123");
var code = rep.StatusCode;
var header = rep.Headers;
var result = await rep.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
WebClient
static async Task Main(string[] args)
{
WebClient wc = new WebClient();
var a = wc.OpenRead("https://localhost:44353/Test/test?b=123");
StreamReader _read = new StreamReader(a, Encoding.UTF8); //新建一个读取流,用指定的编码读取,此处是utf-8
string str = _read.ReadToEnd();
a.Close();
_read.Close();
Console.WriteLine(str);
}