0

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 呼び出しの 1 つは次のようになります。

// 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無許可

asmx サービスを作成する前に、aspx 経由で使用していましたが、これによりパフォーマンスとシリアライゼーションに関する問題が発生していましたが、一部のサービスでは問題なく動作していました。API では、すべての get リクエストが機能するために認証が必要です。

このアプリへのデモリンク

4

2 に答える 2

1

この問題が発生している他の人は、この行のコメントを外して、WebからWebサービスを呼び出せるようにしてください...

[System.Web.Script.Services.ScriptService]

乾杯

于 2011-11-23T17:42:47.217 に答える
1

1)Webサービスをテストしようとすると、「テストフォームはローカルマシンからのリクエストでのみ使用できます」と表示されます

警告: テストが完了したら、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 を再確認 して、ローカル バージョンの web.config と同じように AppSettings に保存されているPoliceAPIUsernameことを確認します。PoliceAPIPassword

3) データをリクエストしている API が、ライブ Web サービスに対する匿名認証を必要としている可能性があります。ローカルでテストする場合、匿名ユーザーはデフォルトで許可されていると思います。

この記事は、あなたの問題であると思われるものに関連していることがわかりました。

于 2011-06-24T21:16:19.727 に答える