401仅在服务器上未经授权的Webmethod

时间:2011-06-24 21:02:33

标签: jquery asp.net webmethod http-status-code-401

我正在使用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":""}

获取http://hci.me.uk/police/PoliceApi.asmx/requestLastTimeUpdated

401未经授权

在制作asmx服务之前,我通过aspx使用它们,虽然这会导致一些有关性能和序列化的问题,但它曾经适用于某些服务。 API要求对所有获取请求进行身份验证。

Demo link to this app

2 个答案:

答案 0 :(得分:1)

1)当我尝试测试您的网络服务时,它会告诉我:“测试表单仅适用于来自本地计算机的请求”

警告:完成测试后,请不要将web.config保留为

将此添加到web.config中,以便您可以在localhost:

之外测试Web服务
   <configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
   </configuration>

然后,去这里测试:http://hci.me.uk/police/PoliceApi.asmx?op=requestLastTimeUpdated

测试后,出于安全原因从web.config中删除这些行。

2)仔细检查您的实时web.config PoliceAPIUsernamePoliceAPIPassword 存储在AppSettings中与web.config

的本地版本相同

3)也许您要求数据的API需要对您的实时Web服务进行匿名身份验证。我认为在本地测试时默认允许匿名用户。

我发现this article与我认为可能是你的问题有关。

答案 1 :(得分:1)

对于遇到此问题的其他人 - 请务必取消注释此行,以确保您可以通过网络调用该网络服务...

[System.Web.Script.Services.ScriptService]

干杯