本文目录
说明
在webapi的实际使用中,可能会存在如下的情况:A公司的程序调用B公司开发的api,api内部处理完相关逻辑后,直接返回一个html的字符串。A公司使用调用WebBrowser控件直接展示。
在这种情况,往往是用在两个联系不是特别紧密的系统中使用。在医疗行业中,最经常遇到的就是HIS调用合理用药、CDSS等系统。
环境说明
VS2022社区版,Win10,.Net.Freamwork 4.7.2。
1、API返回html
1.1 api方法直接返回html串
[HttpGet]
public HttpResponseMessage GetZL(string a)
{
//这儿进行具体的业务逻辑方法
//**********业务逻辑具体代码*******
//下面是具体的返回。
//直接返回一个html串。下面的定义中使用了占位符
string tempContentHtml = @"<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<title>hello world</title>
</head>
<body>
{0}
</body>
</html>";
//这儿的result可以认为是上面api逻辑处理后的结果
List<string> result = new List<string>() { "测试1","ceshi2","测试内容3adfadfa法人法定嘎嘎嘎"};
//将返回结果拼接到html串中
string datahtml = "";
result.ForEach(x => {
datahtml += "<p style='color:red; margin: 20px'>" + x+"</p>";
});
var ContentHtml=string.Format(tempContentHtml, datahtml);
//返回结果
var response = new HttpResponseMessage();
response.Content = new StringContent(ContentHtml);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); //限定类型
return response;
}
1.2 api内部发起一个web请求
[HttpGet]
public HttpResponseMessage GetZL(string a)
{
//业务处理
//进行某些业务处理,并返回XXX的结果
string XXXX=getServiceByString(a);
//使用webclient发起一个请求
string uri =string.format("http://localhost/APIRedirectMVC/withdata/index?id={0}",XXXX); //这儿可以携带参数,然后在这个界面中controller中具体编写参数后面的业务数据
WebClient wc = new WebClient();
Stream resStream = wc.OpenRead(uri);
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string ContentHtml = sr.ReadToEnd(); //读取该业务的html串
var response = new HttpResponseMessage();
response.Content = new StringContent(ContentHtml);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
这个写法和第一个类似,唯一的却别是,api内部是否进行业务跳转。若api只是简单的数据查询,并通过界面展示,则使用第一种即可。若需要进行业务处理的,例如,登录界面,通过调用api后,若未认证,需要跳转至登录界面的业务,则可以使用第二种方案。
1.3 api直接进行跳转的
[HttpGet]
public HttpResponseMessage GetZL(string a)
{
//业务逻辑的代码
//具体跳转的代码
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://localhost/APIRedirectMVC/withdata/index");
return response;
}
这个最简单,直接进行跳转。
2、展示界面
页面展示基本两种形式。1:BS程序直接调用api,然后在新的界面中展示。2:CS程序调用api,然后通过WebBrowser进行展示。
2.1 第一种形式如下:
2.2 WebBrowser展示
效果如下:
按钮里面的逻辑方法如下:
private void button1_Click(object sender, EventArgs e)
{
//发起api请求
string url = @"http://localhost/APIRedirectMVC/api/values/getzl";
string data = "a=123";
string abc= getResponseByHttpGet(url,data);
//结果处理
if (abc != null)
{
//通过webBrowser进行数据展示
this.webBrowser1.Navigate("about:blank");
this.webBrowser1.Document.Write(abc);
}
else
{
this.webBrowser1.Url = new Uri("www.baidu.com");
}
}
3、代码下载
涉及的两个工程师,api的程序和winform的。
下载地址分别为:
链接:api的程序
提取码:zlnh
链接:winform
提取码:zlnh
以上
2022年4月18日