相关疑难解决方法(0)

在 C# 中使用基本身份验证调用 WEB API

我有一个我编写的工作 WEB API,我向 API 添加了基本身份验证(用户名是“testing”,密码是“123456”)。但是,当尝试从我的 Web 表单调用该 API 时,我不断收到“(401) Unauthorized”消息。我应该在 Web 代码中更改什么才能成功调用 API?

 string url = String.Format("http://example.com"); //here I have the correct url for my API
 HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
 requestObj.Method = "Get";
 requestObj.PreAuthenticate = true;
 requestObj.Credentials = new NetworkCredential("testing", "123456");
 HttpWebResponse responseObj = null;
 responseObj = (HttpWebResponse)requestObj.GetResponse();
 string strresult = null;
 using (Stream stream = responseObj.GetResponseStream())
 {
     StreamReader sr = new StreamReader(stream);
     strresult = sr.ReadToEnd();
     sr.Close();
 }
Run Code Online (Sandbox Code Playgroud)

这是我的 API 在身份验证方面搜索的内容:

actionContext.Request.Headers.Authorization.Parameter
Run Code Online (Sandbox Code Playgroud)

我应该添加一个标头而不是 NetworkCredential 还是同样的事情?

c# asp.net credentials basic-authentication asp.net-web-api

9
推荐指数
1
解决办法
4万
查看次数