asp.net core webapi项目

1.项目Startup文件 ConfiguratureService() 添加

public void ConfigureServices(IServiceCollection services)
{
      services.AddMvc(opt =>
     {
           o.Filters.Add(new Rs.AspNetCore.AppExceptionFilter());
           //统一输入内容格式
           o.InputFormatters.Insert(0, new RsInputFormatter());
           //统一的消息返回格式
           o.OutputFormatters.Insert(0, new RsOutputFormatter("yyyy-MM-dd"));
     }) 
}
  1. api的消息将统一返回如下格式
{
  "success":true
  ,"code":200
  ,"msg":"your custom msg"
  ,"targetUrl":null
  ,"result":"your custom result object"
}

仅对请求是/api/开头的路径有效

POST请求,服务端参数定义[FormBody]Class model

客户端要保证 header中"Content-Type":"application/json;charset=utf-8"

$.ajax({
            url: '/api/password/change',
                type: 'put',
                data: JSON.stringify(data.field), //转字符,否则可能出现400
                contentType: 'application/json',  //不写可能出现415
                success: function(ret) {
                    if (ret.success)
                    {
                        layer.msg(ret.msg, { icon: 1,time: 3000})
                    }
                    else
                    {
                        layer.msg(ret.msg, { icon: 2, time: 3000 });
                    }
                },
                error: function(err) { }
            });

客户端的参数如果是json,要转成字符串后发送到服务器,例var d=JSON.stringify(data);

asp.net core mvc项目

services.AddMvc()
                .AddJsonOptions(options => {
                    //数据格式首字母小写
                    options.JsonSerializerOptions.PropertyNamingPolicy =JsonNamingPolicy.CamelCase;
                    //数据格式原样输出
                    //options.JsonSerializerOptions.PropertyNamingPolicy = null;
                    //取消Unicode编码
                    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                    //忽略空值
                    options.JsonSerializerOptions.IgnoreNullValues = true;
                    //允许额外符号
                    options.JsonSerializerOptions.AllowTrailingCommas = true;
                    //反序列化过程中属性名称是否使用不区分大小写的比较
                    options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
                    //mvc返回日期格式
                    options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
                });

results matching ""

    No results matching ""