文章出處
文章列表
業務場景:
在 ASP.NET Core 項目中,所有的代碼都是駱駝命名,比如userName, UserName
,但對于 WebApi 項目來說,因為業務需要,一些請求、查詢和響應參數的格式需要轉換,比如轉換成下劃線命名(又稱為snake case
),比如user_name
。
具體實現:
請求和響應參數格式轉換(請求具體是非get
請求,響應參數一般為json
),ASP.NET Core 實現很簡單,Startup
只需要下面配置代碼:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
NamingStrategy = new SnakeCaseNamingStrategy()
});
}
查詢參數實現比較麻煩點(具體為get
請求,比如users?user_name=xishuai&user_id=1
),實現代碼:
public class RewriteQueryStringMiddleware
{
private readonly RequestDelegate _next;
//Your constructor will have the dependencies needed for database access
public RewriteQueryStringMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var query = context.Request.QueryString;
if (query.HasValue)
{
var parms = string.Join("&", query.Value.TrimStart('?').Split('&').Select(s =>
{
var kv = s.Split('=');
var k = kv[0].Replace("_", "");
var v = kv[1];
return $"{k}={v}";
}));
QueryString newQuery = new QueryString($"?{parms}");
context.Request.QueryString = newQuery;
}
//Let the next middleware (MVC routing) handle the request
//In case the path was updated, the MVC routing will see the updated path
await _next.Invoke(context);
}
}
public static class RewriteQueryStringExtensions
{
public static IApplicationBuilder UseRewriteQueryString(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RewriteQueryStringMiddleware>();
}
}
實現原理就是截獲請求,并對QueryString
轉換和重寫,Startup
中添加配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseRewriteQueryString();
}
參考資料:
文章列表
全站熱搜