C# 带有Web服务的Web API
我编写了下面的代码来调用web服务数据输出,它成功了。问题是当我激活web软件上的api密钥并生成该密钥时,调用web服务并需要使api客户端通过httpRequest请求该密钥,但每当我运行它时,我的问题都会显示“远程服务器返回错误:(404)未找到”。你知道吗?我把我的全部密码贴在下面 事先非常感谢C# 带有Web服务的Web API,c#,web-services,http,client,api-key,C#,Web Services,Http,Client,Api Key,我编写了下面的代码来调用web服务数据输出,它成功了。问题是当我激活web软件上的api密钥并生成该密钥时,调用web服务并需要使api客户端通过httpRequest请求该密钥,但每当我运行它时,我的问题都会显示“远程服务器返回错误:(404)未找到”。你知道吗?我把我的全部密码贴在下面 事先非常感谢 using System; using System.Collections.Generic; using System.ComponentModel; using System.Dat
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DisplayDataInformation
{
public partial class DisplayDataInformation : Form
{
public DisplayDataInformation()
{
InitializeComponent();
}
private void Submit(object sender, EventArgs e)
{
localhost.Dashboard proxy = new localhost.Dashboard();
localhost.ProjectMetaData[] pm = proxy.GetAllProjectMetaData();
const string URL = "http://localhost/myProgram/";
const string apiKey = "d26b15b5-e336-48de-9142-939c0e639e8f";
const string Id = "Id";
const string Pass = "pass";
System.Net.HttpWebRequest myHttpWReq;
System.Net.HttpWebResponse myHttpWResp;
//myHttpWReq.ContentLength = 0;
// Make a web request to the web service
myHttpWReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(BLUEURL + "http://localhost/myProgram/Dashboard.asmx" + Id + Pass + apiKey);
myHttpWReq.Method = "Get";
// Get the response of the web service
myHttpWResp = (System.Net.HttpWebResponse)myHttpWReq.GetResponse();
if (myHttpWResp.StatusCode == System.Net.HttpStatusCode.OK)
{
//Create an XML reader to parse the response
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(myHttpWResp.GetResponseStream());
}
//set an string output to the windows form
StringBuilder sb = new StringBuilder();
foreach (localhost.ProjectMetaData value in pm)
{
sb.AppendLine(value.ProjectTitle + " - "
+ value.ProjectID + " - "
+ value.PublishStatus );
// sb.AppendLine("\r\n\t");
}
label1.Text = sb.ToString();
}
}
}
看起来您最像是错误地生成了请求URL。您已经创建了您的:
myHttpWReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(BLUEURL + "http://localhost/myProgram/Dashboard.asmx" + Id + Pass + apiKey);
此代码生成的URL将是:
http://localhost/myProgram/Dashboard.asmxIdPassd26b15b5-e336-48de-9142-939c0e639e8f
(注意:我在您的代码示例中找不到变量BLUEURL的值,但它将以您正在生成的URL为前缀。我最好的猜测是它是空的,因为否则您将得到一个值。)
这看起来不像您要查找的正确URL,因此出现404错误。您可能想要的是:
myHttpWReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(String.Format("http://localhost/myProgram/Dashboard.asmx?id={0}&pass={1}&apiKey={2}", Id, Pass, apiKey));
这将向URL发送请求
http://localhost/myProgram/Dashboard.asmx
在查询字符串中发送参数
但是,这可能仍然会给您一个错误,因为您试图调用一个基于XML的web服务ASMXWeb服务,因此您的请求的格式错误
将向您展示如何将Dashboard.asmx web服务作为服务引用添加到项目中。这将自动生成一个代理类,该类将把对web服务的所有调用包装为简单的函数调用
请阅读以下答案,以获取有关如何添加参考的更多帮助: