//配置文件
<appSettings>
《《add key="webpages:Version" value="2.0.0.0" /》
《add key="webpages:Enabled" value="false" /》
《add key="PreserveLoginUrl" value="true" /》
《add key="ClientValidationEnabled" value="true" /》
《add key="UnobtrusiveJavaScriptEnabled" value="true" /》
《add key="WebReference.Service.PostUrl" value="http://106.ihuyi.com/webservice/sms.php?method=Submit"/》//重点
</appSettings>
///以上是web.confing中的配置
后台Httpclient访问API代码
public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];//是在web.confing配置的数据
public string yzm(string mobiles)
{
if (mobiles != null)
{
string account = "********";//用户名是登录ihuyi.com账号名(例如:cf_demo123)
string password = "**********************"; //请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
string mobile = mobiles;
Random rad = new Random();//生成随机数
int mobile_code = rad.Next(1000, 10000);
string content = "您的验证码是:" + mobile_code + " 。请不要把验证码泄露给其他人。";//要发送的内容
//Session["mobile"] = mobile;
string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}&format={4}";//拼接字符串形成请求体
using (HttpClient client = new HttpClient())//用客户端请求API数据
{
//进行utf-8进行编码解析;因为API接口需要密文以字节数组的形式发送
UTF8Encoding encoding = new UTF8Encoding();
//将请求体编码成字节数组
byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content, "json"));
//设置请求体
HttpContent contents = new ByteArrayContent(postData, 0, postData.Length);
//设置请求头(包头)成字节数组
contents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
//请求结果
var result = client.PostAsync(PostUrl, contents).Result;
//判断请求结果的状态码
if (result.IsSuccessStatusCode)
{
//返回的json结果
var jj = result.Content.ReadAsStringAsync().Result;
//已发送的验证码
//Session["mobile_code"] = mobile_code;//可以那此值与客户输入的验证码作比较。
return jj;
}
else
{
var jj = result.StatusCode;
return Newtonsoft.Json.JsonConvert.SerializeObject("code:1");
}
}
}
return Newtonsoft.Json.JsonConvert.SerializeObject({"code:1"});
}