长链接生成短链接
效果是: 输入长链接 生成短链接
长链接: https://m.mbmb.top/detail?id=08d60331-fd57-d002-90c9-275104af0d1b
生成的短链接: http://t.cn/E4lQODq
此处用的是新浪的api,需要自己申请sharSource(跟appId一样)
代码:
ShortLinkVM如下:
namespace ViewModels
{
/// <summary>
/// 短链接生成
/// </summary>
public class ShortLinkVM
{
/// <summary>
/// 短链接url
/// </summary>
public string Url_short { get; set; }
/// <summary>
/// 长链接url
/// </summary>
public string Url_long { get; set; }
/// <summary>
/// 类型
/// </summary>
public int Type { get; set; }
}
}
public Response<ShortLinkVM> ShortLink(string url)
{
if (string.IsNullOrEmpty(url))
{
return FastResponse.Response(HttpStatusCode.BadRequest,new ShortLinkVM { }, "url不能为空");
}
var sharSource = GetSystemConfig.GetChildConfig<string>("WeChatSharSource");
if (string.IsNullOrEmpty(sharSource))
{
return FastResponse.Response(HttpStatusCode.BadRequest, new ShortLinkVM { }, "redis配置没有加上");
}
//api地址
var address = "http://api.t.sina.com.cn/short_url/shorten.json?source="+ sharSource;
address += "&url_long=" + HttpUtility.UrlEncode(url);
UTF8Encoding encoding = new UTF8Encoding();
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(address);
myRequest.Method = "GET";
myRequest.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
string srcString = reader.ReadToEnd();
reader.Close();
//json转换
// var urls = JsonHelper.Deserialize<List<sina_short_url>>(json);
if (srcString != null)
{
var result = JsonConvert.DeserializeObject<List<ShortLinkVM>>(srcString);
return FastResponse.Response(HttpStatusCode.OK, result[0]);
}
return FastResponse.Response<ShortLinkVM>(HttpStatusCode.BadRequest);
}