ASP.NET Core 请求/查询/响应参数格式转换(下划线命名)

时间:2021-09-29 03:02:28

业务场景:

在 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();
}

参考资料: