Last active
April 26, 2021 20:07
-
-
Save Ryanman/661e770ab9943098b2d7a2d6170006be to your computer and use it in GitHub Desktop.
Create a snake-case HTTP response in ASP.NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using Newtonsoft.Json.Serialization; | |
using System.Net.Http; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Hylaine.Shared.Extensions | |
{ | |
public static class HttpResponseExtensions | |
{ | |
public static async Task<HttpResponseMessage> PostAsJsonAsync<TModel>(this HttpClient client, string requestUrl, TModel model) | |
{ | |
var json = JsonConvert.SerializeObject(model); | |
var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); | |
return await client.PostAsync(requestUrl, stringContent); | |
} | |
public static string ToSnakeCase(this string input) | |
{ | |
if (string.IsNullOrEmpty(input)) | |
return input; | |
var buffer = ""; | |
for (var i = 0; i < input.Length; i++) | |
{ | |
var isLast = (i == input.Length - 1); | |
var isSecondFromLast = (i == input.Length - 2); | |
var curr = input[i]; | |
var next = !isLast ? input[i + 1] : '\0'; | |
var afterNext = !isSecondFromLast && !isLast ? input[i + 2] : '\0'; | |
buffer += char.ToLower(curr); | |
if (!char.IsDigit(curr) && char.IsUpper(next)) | |
{ | |
if (char.IsUpper(curr)) | |
{ | |
if (!isLast && !isSecondFromLast && !char.IsUpper(afterNext)) | |
buffer += "_"; | |
} | |
else | |
buffer += "_"; | |
} | |
if (!char.IsDigit(curr) && char.IsDigit(next)) | |
buffer += "_"; | |
if (char.IsDigit(curr) && !char.IsDigit(next) && !isLast) | |
buffer += "_"; | |
} | |
return buffer; | |
} | |
public static async Task<T> ReadSnakeCaseAsAsync<T>(this HttpContent content) | |
{ | |
var settings = new JsonSerializerSettings | |
{ | |
ContractResolver = new SnakeCaseContractResolver(), | |
DateFormatHandling = DateFormatHandling.IsoDateFormat | |
}; | |
var json = await content.ReadAsStringAsync(); | |
var obj = JsonConvert.DeserializeObject<T>(json, settings); | |
return obj; | |
} | |
} | |
public class SnakeCaseContractResolver : DefaultContractResolver | |
{ | |
protected override string ResolvePropertyName(string propertyName) | |
{ | |
return propertyName.ToSnakeCase(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment