其他分享
首页 > 其他分享> > WebApi Mvc Controller httpclient 数据交互

WebApi Mvc Controller httpclient 数据交互

作者:互联网

 

客户端调用:

public T callOuterInterface<T>(string fullUrl, string jsonstr)
{
HttpClient client = new HttpClient();
try
{
using (StringContent sc = new StringContent(jsonstr))
{
sc.Headers.ContentType = new MediaTypeHeaderValue("application/json");// "application/x-www-form-urlencoded");
Raize.CodeSiteLogging.CodeSite.Send(fullUrl);
var respMsg = client.PostAsync(fullUrl, sc);


if (respMsg.Result.StatusCode == System.Net.HttpStatusCode.OK)
{
string result = respMsg.Result.Content.ReadAsStringAsync().Result;
result = Regex.Unescape(result); --去掉转义字符
if (result.StartsWith("\"")) result = result.Substring(1, result.Length-1);  --去掉头字符“引号”
if (result.EndsWith("\"")) result = result.Substring(0, result.Length-1);--去掉尾字符“引号”
Common.CShare.nlogger.Debug("result:" +result);
var ret = JsonConvert.DeserializeObject<T>(result);
return ret;
}
return default;
}
}
catch (Exception e)
{
Common.CShare.nlogger.Debug("异常:" + e.Message);
return default;
}
finally
{
client.Dispose();
}
}
}

webapi contoller:

public class TestController : ApiController
{


[HttpPost]
public string mainintf( string func)
{
--接收通过httpcontent传入的json
string val = Request.Content.ReadAsStringAsync().Result;

string resultstr = "";
if (!string.IsNullOrWhiteSpace(val))
{

DataShare.loghelper.Debug("preparing ");

switch (func)
{
case "VerifyUserLogin":
resultstr = VerifyUserLogin(val);
DataShare.loghelper.Debug("ret =" + resultstr);

return resultstr;

return "";

default:
//方法调用错误,无此方法
break;
}

}
return resultstr;

}

 

注: webapi Controller 与 mVC Controller 返回的json串不同,webapi返回的字符串经过了转义,中间加上了很多的转义符号,使用时需要去掉。

 

仅供参考

 

标签:WebApi,return,string,--,Controller,Mvc,result,Debug,resultstr
来源: https://www.cnblogs.com/sunalways/p/14601124.html