![](/img/trans.png)
[英]jQuery convert data-* attributes to lower camel case properties
[英]Connection response properties are camel case
我不知道為什么會這樣。 我正在將我的angular 4應用程序從托管服務器連接到signalR集線器,它的工作原理就像一個超級按鈕(2.2.2版)
我現在必須向另一個項目添加第二個signalR連接,並且由於某些未知的原因,響應的屬性全部是camelCase而不是PascalCase。 但是,jquery.signalr-2.2.2.js文件期望它們為PascalCase,並拋出服務器版本“未定義”的錯誤。
由於他正在尋找res.ProtocolVersion,因此“未定義”是合乎邏輯的,並且該屬性在我的反序列化響應中不存在。 但是,我確實有一個res.protocolVersion,它擁有他需要的確切值。
我為此已經浪費了很多時間,我們非常感謝您的幫助!
編輯:@ rory-mccrossan 我想了很多,這就是為什么我注釋掉了服務器端的json序列化器/格式化程序代碼,但無濟於事。
我正在考慮下一個建議
因此,在羅瑞(Rory)的提示下,我在互聯網上搜索了更多內容,當然,其他人也遇到了這個問題:
但是,該解決方案不適用於我:/
然后,我找到了一個類似的解決方案,但是在這里,您將始終具有默認的合同解析器,除非對象來自某個庫(帶有視圖模型的庫)。 https://blogs.msdn.microsoft.com/stuartleeks/2012/09/10/automatic-camel-casing-of-properties-with-signalr-hubs/
注意:這不是理想的解決方案,但它是最適合我的情況的解決方案
因此,我想出了一個新的解決方案,它與存在問題的現有代碼很好地結合在一起。
解決此問題的另一種方法是讓您的應用使用DefaultContractResolver
。 SignalR現在將連接,但是您的其他應用程序將中斷。 為了緩解該問題,我正在使用兩種簡單的擴展方法。
首先,我擴展了HttpConfiguration
類,以換出CamelCasePropertyNamesContractResolver
的格式化程序
public static class HttpConfigurationExtensions
{
public static HttpConfiguration ToCamelCaseHttpConfiguration(this HttpConfiguration configuration)
{
var jsonFormatter = configuration.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
bool needToAddFormatter = jsonFormatter == null;
if (needToAddFormatter)
{
jsonFormatter = new JsonMediaTypeFormatter();
}
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
if (needToAddFormatter)
{
configuration.Formatters.Add(jsonFormatter);
}
return configuration;
}
}
現有的Web API將始終返回HttpResponseMessage
,這就是為什么我可以像以前那樣處理它。
api調用示例
[Route("")]
[HttpPost]
public async Task<HttpResponseMessage> CreateSetting(Setting setting)
{
// the response object is basically the data you want to return
var responseData = await ...
return Request.CreateResponse(responseData.StatusCode, responseData);
}
我注意到每個Api調用都使用Request.CreateResponse(...)
方法。 我沒有立即看到的是Microsoft實際上已經預見到了所有必要的重載,這意味着我不能只做自己的Request.CreateResponse(...)
實現。
這就是為什么它被稱為MakeResponse
public static class HttpRequestMessageExtensions
{
public static HttpResponseMessage MakeResponse<T>(this HttpRequestMessage request, T response) where T : Response
{
return request.CreateResponse(response.StatusCode, response,
request.GetConfiguration().ToCamelCaseHttpConfiguration());
}
}
Response
類是您希望api返回的數據結構。 在我們的api中,它們全都包裹在這些結構之一中。 這會導致api的響應類似於Slack API上的響應。
因此,現在所有控制器都使用Request.MakeResponse(responseData)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.