ASP.NET MVC3 HttpWebRequest-需要帮助 [英] ASP.NET MVC3 HttpWebRequest - Help Needed

查看:63
本文介绍了ASP.NET MVC3 HttpWebRequest-需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用mapquest应用,在客户端,我有以下Ajax请求:

Hi,

I''m working with a mapquest App, and on the client side, i have the following Ajax Request:

$.ajax({
                            url: 'http://www.mapquestapi.com/search/v1/radius',
                            dataType: 'jsonp',
                            crossDomain: true,
                            data:
                            {
                                key: decodeURI('MyKey'),
                                origin: city + ', ' + state,
                                radius: 300,
                                hostedData: 'MyData',
                                maxMatches: 4
                            },
                            success: jsonResponse
                        });



对于上述调用,jsonResponse函数启动并运行良好.

现在,我想在ASP.NET MVC3 Web App中将其作为服务器端例程.

我编写了以下代码来模仿客户端:



For the above call, jsonResponse function kicks in and works perfectly well.

Now, i want to make this a server side routine in my ASP.NET MVC3 Web App.

I''ve Written the following code to imitate client side:

 requestUrl = @"http://www.mapquestapi.com/search/v1/radius";

// Create Request
var request = HttpWebRequest.Create(requestUrl);

request.Method = "POST";

// Set method type for request
request.ContentType = "application/json";

var options  = new
{

    key = HttpUtility.UrlDecode("MyKey"),
    origin = requestvm.City + "," + requestvm.State,
    radius = 300,
    hostedData = "MyData",
    maxMatches = 4
};

// Using Newtonsoft.Json
var jsonobj = JsonConvert.SerializeObject(options);
try
{
    using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream()))
    {
        requestWriter.Write(jsonobj);
    }
}
catch (System.Net.WebException ex)
{
    return null;
}

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    if (response.StatusCode != HttpStatusCode.OK)
    {
        ModelState.AddModelError("", "Request Staus was not OK. Please try again");
        return View(requestvm);
    }

    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        var serverResponse = reader.ReadToEnd();


        var responseData = JsonConvert.DeserializeObject(serverResponse);

        return null;
    }

}



因此,当我执行断点检查var responseData时,我从Mapquest收到一条错误消息,提示您需要提供Key参数.谁能告诉我为什么Key参数在服务器端不起作用,而在客户端上起作用?

任何建议表示赞赏.谢谢.



So when i do a breakpoint check var responseData, i get an error message from Mapquest, saying you need to provide the Key parameter. Can anyone tell me why the Key param is not working on the server side, but it is on the client?

Any suggestions are appreciated. Thanks.

推荐答案

.ajax({ 网址:' http://www.mapquestapi.com/search/v1/radius', dataType:' jsonp', crossDomain: true , 数据: { 键:decodeURI(' MyKey'), 来源:城市+ ' ,' +省, 半径: 300 , hostedData:' MyData', maxMatches: 4 }, 成功:jsonResponse });
.ajax({ url: 'http://www.mapquestapi.com/search/v1/radius', dataType: 'jsonp', crossDomain: true, data: { key: decodeURI('MyKey'), origin: city + ', ' + state, radius: 300, hostedData: 'MyData', maxMatches: 4 }, success: jsonResponse });



对于上述调用,jsonResponse函数启动并运行良好.

现在,我想在ASP.NET MVC3 Web App中将其作为服务器端例程.

我编写了以下代码来模仿客户端:



For the above call, jsonResponse function kicks in and works perfectly well.

Now, i want to make this a server side routine in my ASP.NET MVC3 Web App.

I''ve Written the following code to imitate client side:

 requestUrl = @"http://www.mapquestapi.com/search/v1/radius";

// Create Request
var request = HttpWebRequest.Create(requestUrl);

request.Method = "POST";

// Set method type for request
request.ContentType = "application/json";

var options  = new
{

    key = HttpUtility.UrlDecode("MyKey"),
    origin = requestvm.City + "," + requestvm.State,
    radius = 300,
    hostedData = "MyData",
    maxMatches = 4
};

// Using Newtonsoft.Json
var jsonobj = JsonConvert.SerializeObject(options);
try
{
    using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream()))
    {
        requestWriter.Write(jsonobj);
    }
}
catch (System.Net.WebException ex)
{
    return null;
}

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    if (response.StatusCode != HttpStatusCode.OK)
    {
        ModelState.AddModelError("", "Request Staus was not OK. Please try again");
        return View(requestvm);
    }

    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        var serverResponse = reader.ReadToEnd();


        var responseData = JsonConvert.DeserializeObject(serverResponse);

        return null;
    }

}



因此,当我执行断点检查var responseData时,我从Mapquest收到一条错误消息,提示您需要提供Key参数.谁能告诉我为什么Key参数在服务器端不起作用,而在客户端上起作用?

任何建议表示赞赏.谢谢.



So when i do a breakpoint check var responseData, i get an error message from Mapquest, saying you need to provide the Key parameter. Can anyone tell me why the Key param is not working on the server side, but it is on the client?

Any suggestions are appreciated. Thanks.


我昨天确实设法解决了这个问题.我这是一个错误.在JQuery.Ajax()调用中检查了数据的帮助后,发现数据将所有内容作为查询字符串放置/追加,如果不是字符串,则Json对其进行序列化.



关于mapquest,我检查了他们是否没有POST请求(我不确定这样做,必须进行更多研究,因为这是完成任务的更安全的方法).



我的工作代码如下:

I did manage to solve this yesterday. It was a mistake on my part. After checking help for data at JQuery.Ajax() calls, found out that data puts/appends all it''s contents as Query string, and it Json serializes it if it''s not already a string.



Regarding mapquest, i checked that they dont have POST requests (i''m not sure of this, have to research more as this is a much safer way to get things done).



My working code is below:

                string key = HttpUtility.UrlDecode("MyKey"); 
                string hostedData = "MyHosted,MySpecificField";
                // example: "MQA.MQ_999_Sample,T=3500" 

                string radius = "300"; 
                string maxMatches = "1"; 
                string origin = 
                HttpUtility.UrlDecode(requestvm.City + "," + requestvm.State); 
 
   requestUrl = @"http://www.mapquestapi.com/search/v1/radius?key=" + key 
                                + "&hostedData=" + hostedData 
                                + "&radius=" + radius 
                                + "&maxMatches=" + maxMatches 
                                + "&origin=" + origin; 
 
                // Create Request 
                var request = HttpWebRequest.Create(requestUrl); 
 
                // set request method 
                request.Method = "GET"; 
 
                // set content type 
                request.ContentType = "application/x-www-form-urlencoded"; 
                
                // get response for GET request 
                using (HttpWebResponse response = 
                       request.GetResponse() as HttpWebResponse) 
                { 
                    if (response.StatusCode != HttpStatusCode.OK) 
                    { 
                        ModelState.AddModelError("",
                        "Request Staus was not OK. Please try again"); 
                        return View(requestvm); 
                    } 
 
                    using (StreamReader reader = 
                    new StreamReader(response.GetResponseStream())) 
                    { 
                        var serverResponse = reader.ReadToEnd(); 
 
                        RadiusResponse radiusResponse = new RadiusResponse(); 
 
                radiusResponse =  
                JsonConvert.DeserializeObject<radiusresponse>(serverResponse); 
                         
                /* at this point, radiusResponse contains the correct
                   response from server. 
                   I also modeled RadiusReponse, as POCO to mimic the 
                   response structure sent from mapquest 
                   (which i got the idea from a GoogleMap api help post). 
                   The advantage of this is that 
                   JsonConvert.Deserialize will now populate each 
                   and every RadiusReponse POCO structure, and now we
                   can use it in a typesafe way. 
                */ 
                } 
          }
</radiusresponse>


这篇关于ASP.NET MVC3 HttpWebRequest-需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆