401 未经授权的 Webmethod 仅在服务器上
我正在使用 jQuery 从 API 获取一些数据。
流读取器验证对 api 的调用并获取如下所示的流:
public string StreamManagerUrlHandler(string requestUrl)
{
try
{
Uri reUrl = new Uri(requestUrl);
WebRequest webRequest;
WebResponse webResponse;
webRequest = HttpWebRequest.Create(reUrl) as HttpWebRequest;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.ContentType = "application/x-www-form-urlencoded";
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
webRequest.Credentials = new NetworkCredential(
ConfigurationManager.AppSettings["PoliceAPIUsername"].ToString(),
ConfigurationManager.AppSettings["PoliceAPIPassword"].ToString());
// Return the response.
webResponse = webRequest.GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), encode))
{
string results = reader.ReadToEnd();
reader.Close();
webResponse.Close();
return results;
}
}
catch (Exception e)
{
return e.Message;
}
}
我的服务如下所示:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[System.Web.Script.Services.ScriptService]
[ScriptService()]
public class PoliceApi : System.Web.Services.WebService {
public PoliceApi () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string requestLocalCrime(string lat, string lng)
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/crimes-street/all-crime?lat=" + lat + "&lng=" + lng + "");
}
// Method for getting the data database was Last updated
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public String requestLastTimeUpdated()
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/crime-last-updated");
}
// Method for getting the data database was Last updated
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public String locateNeighbourhood(string lat, string lng)
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/locate-neighbourhood?q=" + lat + "%2C" + lng + "");
}
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string neighbourhoodTeam(string force, string neighbourhood)
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/" + force + "%2F" + neighbourhood + "%2F" + "people");
}
}
作为示例,其中一个 jQuery ajax 调用如下所示:
// Getting last time the API data was updated
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "../police/PoliceApi.asmx/requestLastTimeUpdated",
dataType: "json",
success: function (data) {
PoliceApp.mapForm.data('lastupdated', $.parseJSON(data.d).date);
},
error: function (res, status) {
if (status === "error") {
// errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
var errorMessage = $.parseJSON(res.responseText);
alert(errorMessage.Message);
}
}
});
本地一切正常。当我将内容上传到远程服务器时,我得到:
{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
GET http://hci.me。 uk/police/PoliceApi.asmx/requestLastTimeUpdated
401 Unauthorized
在制作 asmx 服务之前,我通过 aspx 使用它们,尽管这导致了一些有关的问题性能和序列化,它曾经对某些服务运行良好。 API 需要身份验证才能使所有获取请求正常工作。
I am using jQuery to get some data from an API.
The stream reader authenticates the calls to the api and gets the stream like this:
public string StreamManagerUrlHandler(string requestUrl)
{
try
{
Uri reUrl = new Uri(requestUrl);
WebRequest webRequest;
WebResponse webResponse;
webRequest = HttpWebRequest.Create(reUrl) as HttpWebRequest;
webRequest.Method = WebRequestMethods.Http.Get;
webRequest.ContentType = "application/x-www-form-urlencoded";
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
webRequest.Credentials = new NetworkCredential(
ConfigurationManager.AppSettings["PoliceAPIUsername"].ToString(),
ConfigurationManager.AppSettings["PoliceAPIPassword"].ToString());
// Return the response.
webResponse = webRequest.GetResponse();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), encode))
{
string results = reader.ReadToEnd();
reader.Close();
webResponse.Close();
return results;
}
}
catch (Exception e)
{
return e.Message;
}
}
My Services look like this:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[System.Web.Script.Services.ScriptService]
[ScriptService()]
public class PoliceApi : System.Web.Services.WebService {
public PoliceApi () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string requestLocalCrime(string lat, string lng)
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/crimes-street/all-crime?lat=" + lat + "&lng=" + lng + "");
}
// Method for getting the data database was Last updated
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public String requestLastTimeUpdated()
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/crime-last-updated");
}
// Method for getting the data database was Last updated
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public String locateNeighbourhood(string lat, string lng)
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/locate-neighbourhood?q=" + lat + "%2C" + lng + "");
}
[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string neighbourhoodTeam(string force, string neighbourhood)
{
StreamManager streamMan = new StreamManager();
return streamMan.StreamManagerUrlHandler("http://policeapi2.rkh.co.uk/api/" + force + "%2F" + neighbourhood + "%2F" + "people");
}
}
And one of the jQuery ajax calls as an example looks like this:
// Getting last time the API data was updated
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "../police/PoliceApi.asmx/requestLastTimeUpdated",
dataType: "json",
success: function (data) {
PoliceApp.mapForm.data('lastupdated', $.parseJSON(data.d).date);
},
error: function (res, status) {
if (status === "error") {
// errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
var errorMessage = $.parseJSON(res.responseText);
alert(errorMessage.Message);
}
}
});
Everything works fine locally. when I upload the stuff to the remote server I get:
{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
GET http://hci.me.uk/police/PoliceApi.asmx/requestLastTimeUpdated
401 Unauthorized
Prior to making the asmx services, I had them being used via aspx although this was causing some issues regarding performance and serialization, it used to work fine for some of the services. The API requires authentication for all get requests to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1) 当我尝试测试你的网络服务时,它告诉我:“测试表单仅适用于来自本地计算机的请求”
警告:不要像这样离开你的 web.config完成测试后将
其添加到 web.config 中,以便您可以在 localhost 之外测试 Web 服务:
然后,转到此处进行测试:http://hci.me.uk/police/PoliceApi.asmx?op=requestLastTimeUpdated
测试后,出于安全原因,从 web.config 中删除这些行。
2) 仔细检查您的实时 web.config,确保
PoliceAPIUsername
和PoliceAPIPassword
存储在 AppSettings 中,与本地版本的 web.config 中的存储方式相同
3) 也许您请求数据的 API 需要对实时 Web 服务进行匿名身份验证。我认为本地测试时默认允许匿名用户。
我发现这篇文章与我认为可能是您的问题相关。
1) When, I try to test your webservice it tells me: "The test form is only available for requests from the local machine"
Warning: Don't leave your web.config like this after you are done testing
Add this in to web.config so you can test the webservice outside of localhost:
Then, go here to test: http://hci.me.uk/police/PoliceApi.asmx?op=requestLastTimeUpdated
After testing, remove those lines from web.config for security reasons.
2) Double-check your live web.config that the
PoliceAPIUsername
andPoliceAPIPassword
are stored in AppSettings the same as in your local version of web.config
3) Maybe the API you are requesting data from needs anonymous authentication to your live web services. I think anonymous users are allowed by default when testing locally.
I found this article related to what I think might be your problem.
对于遇到此问题的其他人 - 请确保取消注释此行,以确保您可以从 Web 调用 Web 服务...
[System.Web.Script.Services.ScriptService]
干杯
For anyone else experiencing this issue - make sure you uncomment this line to ensure you can call the web service from the web...
[System.Web.Script.Services.ScriptService]
Cheers