Essay background: Because there is a simple function of the project is to implement the Chinese simplified to traditional switching, the database is stored in the source data is Simplified Chinese, in order to save trouble on the way to control the API Httpheader to return the corresponding traditional data.
Implementation: The HttpResponse is intercepted by the middleware in ASP. NET Core, and then the Chinese traditional switch is realized by converting character encoding.
The implementation code is as follows:
Httpcontextmiddleware Middleware
Public classHttpcontextmiddleware {Private ReadOnlyrequestdelegate _next; PublicHttpcontextmiddleware (requestdelegate next) {_next=Next; } Public AsyncTask Invoke (HttpContext context) {varOriginalbodystream =context. Response.body; using(varResponsebody =NewMemoryStream ()) {context. Response.body=responsebody; await_next (context); varresult =awaitFormatresponse (context. Response); if(context. Request.Headers.Keys.Contains (Constants.httpheaderlanguage)) {varLang = context. Request.Headers.GetCommaSeparatedValues (Constants.httpheaderlanguage). GetValue (0). ToString (); if(lang = ="ZH-TW") { varTraditionresult =converthelper.totraditional (Result); byte[] Array =Encoding.UTF8.GetBytes (Traditionresult); MemoryStream Stream=NewMemoryStream (array); Try { awaitStream. Copytoasync (Originalbodystream); } Catch(Exception ex) {Throwex; } } Else { Try { awaitResponsebody.copytoasync (Originalbodystream); } Catch(Exception ex) {Throwex; } } } Else { awaitResponsebody.copytoasync (Originalbodystream); } } } Private Asynctask<string>Formatresponse (HttpResponse response) {Response. Body.seek (0, Seekorigin.begin); varText =await NewStreamReader (response. Body). Readtoendasync (); Response. Body.seek (0, Seekorigin.begin); return$"{text}"; } }
Startup.cs
Public void Configure (Iapplicationbuilder app, ihostingenvironment env) { app. Usedefaultfiles (); App. Useauthentication (); App. Usestaticfiles (); // injected into the pipeline before MVC App. Usemiddleware(); App. Usemvc (); }
Converthelper Chinese Simplified and traditional conversion tool class
Public Static classConverthelper {Private Const intLocale_system_default =0x0800; Private Const intLcmap_simplified_chinese =0x02000000; Private Const intLcmap_traditional_chinese =0x04000000; [DllImport ("kernel32", CharSet = CharSet.Auto, SetLastError =true)] Private Static extern intLCMapString (intLocale,intDwmapflags,stringLPSRCSTR,intCCHSRC, [out]stringLPDESTSTR,intcchdest); /// <summary> ///convert characters to Simplified Chinese/// </summary> /// <param name= "source" >Enter the string to convert</param> /// <returns>string after conversion is complete</returns> Public Static stringTosimplified (stringsource) {String target=NewString (' ', source. Length); intRET =lcmapstring (Locale_system_default, Lcmap_simplified_chinese, source, source. Length, Target, source. Length); returnTarget; } /// <summary> ///convert characters to Traditional Chinese/// </summary> /// <param name= "source" >Enter the string to convert</param> /// <returns>string after conversion is complete</returns> Public Static stringTotraditional (stringsource) {String target=NewString (' ', source. Length); intRET =lcmapstring (Locale_system_default, Lcmap_traditional_chinese, source, source. Length, Target, source. Length); returnTarget; } }
The above source code is all the key code, after the middleware injection, no longer in action or the controller to intercept alone, tested, will intercept all the API response results. Here's an episode where I tried to intercept with Resultfilter, but I couldn't intercept the response after the response. For some reason, I finally gave up the filter method and chose the way to intercept this middleware.
This article refers to the following:
Https://elanderson.net/2017/02/log-requests-and-responses-in-asp-net-core/
If there is something wrong with this article, please correct me! willing to share with June.
Finally, thank you for reading!
ASP. NET Core 2.0 implements HttpResponse switching