在本地IIS上发布一个HTML网站和WebService接口并对接的方法。
一、编写WebService接口,用的是VS2019。
新建一个空网站,添加一个WEN服务(ASMX),编写一个方法从数据库获取数据,这是我的方法:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService] //这一句本来是注释掉的,但要用AJAX就必须取消注释
public class forWeb : System.Web.Services.WebService
{
[WebMethod]
public string selDP()
{
SQLconn con = new SQLconn();
DataTable dt = con.getData();
string JsonString = string.Empty;
JsonString = JsonConvert.SerializeObject(dt);
return JsonString;
}
}
因为要被AJAX调用,所以需要设置Web.config,加一些代码,如下:
<configuration>
<system.web>
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type,Accept"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
配置跨域…
<configuration>