这个本来是在网上下载的 SpoonySonny 的 GoogleSlugTransliterator 插件,但众所周知,Google的API收费了,所以咱们这些穷人都用不起了,网上查查发现Microsoft也有提供翻译API并且不收费,权且用Bing的API代替吧。
BingSlugTransliterator.cs代码如下(双斜线注释的部分是原来GoogleAPI的,万一哪天GG又免费了咱接着用,嘿嘿):
#region using using System; using System.Web; using System.Web.UI; using BlogEngine.Core.Web.Controls; using BlogEngine.Core; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Net; #endregion /// <summary> /// Transliterate post Chinese slug into English /// </summary> [Extension("使用 Bing Api 将标题自动翻译并转换为英文别名", "1.0", "<a href="https://dabao.me">小火柴.NET</a>")] public class BingSlugTransliterator { /// <summary> /// Hooks up an event handler to the Post.Serving event. /// </summary> static BingSlugTransliterator() { Post.Saving += new EventHandler<SavedEventArgs>(Post_Saving); } /// <summary> /// Handles the Post.Saving event. /// </summary> private static void Post_Saving(object sender, SavedEventArgs e) { Post post = (Post)sender; if (post.New) { try { WebClient wb = new WebClient(); //string url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=zh%7Cen&q={0}"; string url = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=8A058850F59C7EAED9937E6FAD573E356F675E4A&from=zh-cn&to=en&text={0}"; string jsonText = wb.DownloadString(string.Format(url, HttpUtility.UrlEncode(post.Title))); //sample: {"responseData": {"translatedText":"text"}, "responseDetails": null, "responseStatus": 200}; //string responseStatus = jsonText.Substring(jsonText.IndexOf(""responseStatus":"), jsonText.Length - 1 - jsonText.IndexOf(""responseStatus":")).Trim(); //string translatedText = jsonText.Substring(jsonText.IndexOf(""translatedText":""), jsonText.IndexOf("}, "responseDetails"") - jsonText.IndexOf(""translatedText":"")).Trim(); //translatedText = translatedText.Replace(""translatedText":"", string.Empty).Replace(""", string.Empty); //responseStatus = responseStatus.Replace(""responseStatus":", string.Empty).Trim(); string translatedText = Regex.Match(jsonText, @"(?<=\()[^)]*(?=\))").Value; //if (responseStatus == "200") //{ string slug = Utils.RemoveIllegalCharacters(translatedText); if (slug.Length > 30) slug.Substring(0, 30); post.Slug = Utils.RemoveIllegalCharacters(translatedText).ToLower(); //} } catch { // We maybe need to catch some exception } } } }
慢慢领会