開發環境json
Restful Api 的返回結果基本上使用的是 JSON
格式,在 .Net Web Api
中默認的是返回 XML
格式,須要修改一下返回的結果的格式api
JSON
格式在 WebApiConfig
中清除其餘的格式,並添加 JSON
格式bash
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
複製代碼
也能夠去除 XML
格式數據結構
config.Formatters.Remove(config.Formatters.XmlFormatter);
複製代碼
還能夠配置 JSON
數據的格式app
縮進ide
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
複製代碼
駝峯式大小寫測試
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
複製代碼
public static HttpResponseMessage toJson( System.Net.HttpStatusCode code, Result result)
{
var response = Newtonsoft.Json.JsonConvert.SerializeObject(result);
HttpResponseMessage res = new HttpResponseMessage(code);
res.Content = new StringContent(response, Encoding.UTF8, "application/json");
return res;
}
複製代碼
統一的返回結果數據格式,對於 null
添加註解 [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
數據能夠選擇忽略,不返回給客戶端ui
public class Result
{
/// <summary>
/// 錯誤信息
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string err;
/// <summary>
/// 具體的數據
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public object data;
public Result(string err,object data)
{
this.err = err;
this.data = data;
}
}
複製代碼
ActionFilterAttribute
統一處理返回結果public class ResultFilterAttribute : ActionFilterAttribute
{
//在Action處理完相關的數據以後,會在通過這個方法處理
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.ActionContext.Response != null)
{
var data = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
Result result = new Result(null, data);
HttpResponseMessage message = Utils.toJson(System.Net.HttpStatusCode.OK result);
actionExecutedContext.Response = message;
}
}
}
複製代碼
對應的 Controller
或Action
添加對應的註解this
[HttpGet]
[ResultFilter]
public IHttpActionResult AllCategory()
{
IEnumerable<CategoryModel> result = _service.GetAllCategory();//具體的數據
return Ok(result);
}
複製代碼
在進行請求接口時,須要先對提交的數據參數作一些驗證,驗證數據的合法性,若是不合法就再也不經過action,直接返回給客戶端處理。spa
使用FluentValidation作參數驗證
FluentValidation
使用Nuget安裝 FluentValidation.WebApi
須要驗證的數據model
[Validator(typeof(UserReqValidator))]
public class UserReq
{
public string username;
public string password;
}
public class UserReqValidator : AbstractValidator<UserReq>
{
public UserReqValidator()
{
RuleFor(m => m.username).NotEmpty().NotNull().WithMessage("用戶名不能爲空");
RuleFor(m => m.password).NotEmpty().NotNull().MinimumLength(8).WithMessage("密碼不能爲空,長度至少是8位");
}
}
複製代碼
讓 FluentValidation
生效,在 WebApiConfig
中添加以下配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
FluentValidationModelValidatorProvider.Configure(config);
}
}
複製代碼
public class ParamsFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
var result = new Result("參數非法", null);
actionContext.Response = Utils.toJson(System.Net.HttpStatusCode.BadRequest, result);
}
}
}
複製代碼
對應的 Controller
或Action
添加對應的註解,若是參數請求的參數非法,就會直接返回給客戶端,就不會在通過對用的Action
[HttpPost]
[ParamsFilter]
[ResultFilter]
public IHttpActionResult CategoryLevel([FromBody] UserReq req)
{
var ids = _service.GetQuestionIdsByLevel(req);
var result = _questionService.GetQuestionByIds(ids);
return Ok(result);
}
複製代碼
自定義異常數據結構
public class ApiException : Exception
{
public int code;
public string msg;
public ApiException(int code,string msg)
{
this.code = code;
this.msg = msg;
}
}
複製代碼
定義 異常篩選器 ExceptionFilterAttribute
public class ApiExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if(actionExecutedContext.Exception is ApiException)
{
var ex = (ApiException)actionExecutedContext.Exception;
var result = new Result(ex.code, ex.msg, null);
actionExecutedContext.ActionContext.Response = Utils.toJson(result);
}else
{
var ex = actionExecutedContext.Exception;
var result = new Result((int)Error.ReturnValue.內部錯誤, ex.Message, null);
actionExecutedContext.ActionContext.Response = Utils.toJson(result);
}
}
}
複製代碼
對應的 Controller
或Action
添加對應的註解,或者全局配置
使用 Nuget 安裝 Swashbuckle
已經自帶了UI
在 SwaggerConfig
中配置對應的XML路徑
c.IncludeXmlComments(GetXmlCommentsPath());
...
protected static string GetXmlCommentsPath()
{
return System.String.Format(@"{0}\bin\對應的項目名稱.XML", System.AppDomain.CurrentDomain.BaseDirectory);
}
複製代碼
配置好以後,訪問 http://localhost:63380/swagger
就能看多對應的UI,能夠直接測試對應的接口
Authorization
在 SwaggerConfig
中配置
c.ApiKey("apiKey")
.Description("API Key Authentication")
.Name("Authorization")
.In("header");
複製代碼
c.EnableApiKeySupport("Authorization", "header");
複製代碼