C#怎么调用web api?

-一个大坑 2017-06-27 10:13:29
IList<SendCarCost_KM> rideCostInfo = ModelConvertHelper<SendCarCost_KM>.ConvertToModel(_rideCostRepository.GetSendCarCost());
这句把要传的参数查好了,怎么序列化传参,怎么接收回传的值?

var ridecost = {
DERIVENO: $("input[name='DERIVENO']").val(),
PASSENGER_QTY: $("input[name='PASSENGER_QTY']").val(),
DISTANCE: $("input[name='DISTANCE']").val(),
KMCOST: $("input[name='KMCOST']").val(),
};

$.ajax({
type: "post",
url: "/SCRP0103/SaveData",
data: { ridecost: JSON.stringify(ridecost) },

这是以前写的前台序列化
...全文
3312 27 打赏 收藏 转发到动态 举报
写回复
用AI写文章
27 条回复
切换为时间正序
请发表友善的回复…
发表回复
wanghui0380 2017-06-28
  • 打赏
  • 举报
回复
百度 [WebMethod] 看看这玩意是什么,然后看看 [WebMethod] public static Task 又什么资料
-一个大坑 2017-06-28
  • 打赏
  • 举报
回复
引用 21 楼 sp1234 的回复:
所谓“非同步做也无法开始”是指你调用 dooPost 方法的代码。而你根本没有贴出你的代码。 你贴了一大堆 dooPost 内部的代码,根本没有去搞清楚你的页面中应该如何调用它。
打开页面执行查询时自动调用方法,我还在尝试先取到返回值。代码就是网上搜的代码已经贴上了
  • 打赏
  • 举报
回复
所谓“非同步做也无法开始”是指你调用 dooPost 方法的代码。而你根本没有贴出你的代码。 你贴了一大堆 dooPost 内部的代码,根本没有去搞清楚你的页面中应该如何调用它。
  • 打赏
  • 举报
回复
一个 aspx 页面中,你使用什么 async 方法啊?
-一个大坑 2017-06-28
  • 打赏
  • 举报
回复
引用 16 楼 xdashewan 的回复:
[quote=引用 11 楼 happy4944 的回复:]
api别人给的,用网址可以直接访问

無法連接至遠端伺服器,这个错你自己代码报的还是对方返回的,具体的异常信息有吗[/quote]


提示对方拒绝连接,但是我用网址能进

-一个大坑 2017-06-28
  • 打赏
  • 举报
回复
引用 17 楼 hanjun0612 的回复:
[quote=引用 15 楼 happy4944 的回复:] 等了快一个小时,异步后面的断点一直没被触发。
页面上 <%@ Page Async=\"true\" %> 这个你加了? [/quote] 没有,我就想后台接收返回值,然后再做操作。<%@ Page Async=\"true\" %> 这个加在前台任意位置?
正怒月神 2017-06-28
  • 打赏
  • 举报
回复
引用 15 楼 happy4944 的回复:
等了快一个小时,异步后面的断点一直没被触发。
页面上 <%@ Page Async=\"true\" %> 这个你加了?
xdashewan 2017-06-28
  • 打赏
  • 举报
回复
引用 11 楼 happy4944 的回复:
api别人给的,用网址可以直接访问
無法連接至遠端伺服器,这个错你自己代码报的还是对方返回的,具体的异常信息有吗
-一个大坑 2017-06-28
  • 打赏
  • 举报
回复

webapiURL += "/api/orglevel/get?";
                WebAPIRequest request1 = new WebAPIRequest();
                string jsonData1 = request1.Get(webapiURL);
                JavaScriptSerializer serializerl = new JavaScriptSerializer();
                List<EMP_ORG_LV> rst1 = serializerl.Deserialize<List<EMP_ORG_LV>>(jsonData1); 
-一个大坑 2017-06-28
  • 打赏
  • 举报
回复
引用 24 楼 xdashewan 的回复:
[quote=引用 23 楼 happy4944 的回复:] js调用会有跨域问题,C#调用会不会也是这个问题
有别的地址吗,换个地址测试下[/quote] 没有了,我去申请百度天气api测试下
xdashewan 2017-06-28
  • 打赏
  • 举报
回复
引用 23 楼 happy4944 的回复:
js调用会有跨域问题,C#调用会不会也是这个问题
有别的地址吗,换个地址测试下
-一个大坑 2017-06-28
  • 打赏
  • 举报
回复
引用 16 楼 xdashewan 的回复:
[quote=引用 11 楼 happy4944 的回复:] api别人给的,用网址可以直接访问
無法連接至遠端伺服器,这个错你自己代码报的还是对方返回的,具体的异常信息有吗[/quote] js调用会有跨域问题,C#调用会不会也是这个问题
-一个大坑 2017-06-27
  • 打赏
  • 举报
回复
是不是样式不对? 接口样式:链接?param={"regNO":["车牌"],"begin":"开始时间","end":"结束时间"} string ss = HttpPost("链接", "{regNO:[\"车牌\"],begin:\"开始时间\",end:\"结束时间\"}");
-一个大坑 2017-06-27
  • 打赏
  • 举报
回复
引用 4 楼 xdashewan 的回复:
[quote=引用 3 楼 happy4944 的回复:] string ss= HttpPost("我的链接?", "参数?");ss是api的返回结果?
对[/quote] request.GetRequestStream().Write(buffer, 0, buffer.Length); {"無法連接至遠端伺服器"}
xdashewan 2017-06-27
  • 打赏
  • 举报
回复
引用 3 楼 happy4944 的回复:
string ss= HttpPost("我的链接?", "参数?");ss是api的返回结果?
-一个大坑 2017-06-27
  • 打赏
  • 举报
回复
引用 2 楼 xdashewan 的回复:
序列化可以使用DataContractJsonSerializer,参考http://www.cnblogs.com/coderzh/archive/2008/11/25/1340862.html 调用api可以参考http://www.cnblogs.com/MuNet/p/6732338.html

private void button1_Click(object sender, EventArgs e)
        {
           string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}");
        }

        public static string HttpPost(string url, string body)
        {
            //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
       
            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }
string ss= HttpPost("我的链接?", "参数?");ss是api的返回结果?
xdashewan 2017-06-27
  • 打赏
  • 举报
回复
序列化可以使用DataContractJsonSerializer,参考http://www.cnblogs.com/coderzh/archive/2008/11/25/1340862.html 调用api可以参考http://www.cnblogs.com/MuNet/p/6732338.html
-一个大坑 2017-06-27
  • 打赏
  • 举报
回复

/// <summary>  
/// HttpClient实现Post请求(异步)  
/// </summary>  
static async void dooPost()  
{  
    string url = "http://localhost:52824/api/register";  
     //设置HttpClientHandler的AutomaticDecompression  
    var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };  
    //创建HttpClient(注意传入HttpClientHandler)  
    using (var http = new HttpClient(handler))  
    {  
        //使用FormUrlEncodedContent做HttpContent  
        var content = new FormUrlEncodedContent(new Dictionary<string, string>()         
        {    {"Id","6"},  
             {"Name","添加zzl"},  
             {"Info", "添加动作"}//键名必须为空  
         });  
  
        //await异步等待回应  
  
        var response = await http.PostAsync(url, content);  
        //确保HTTP成功状态值  
        response.EnsureSuccessStatusCode();  
        //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)  
        Console.WriteLine(await response.Content.ReadAsStringAsync());  
    }  
} 
网上搜的方法

        /// <summary>  
        /// HttpClient实现Post请求(异步)  
        /// </summary>  
        public async void dooPost()
        {
            IList<SendCarCost_KM> rideCostInfo = ModelConvertHelper<SendCarCost_KM>.ConvertToModel(_rideCostRepository.GetSendCarCost());
            for (int i = 0; i < rideCostInfo.Count; i++)
            {
                string url = "http://121.12.249.239:8000/QueryMileage";
                //设置HttpClientHandler的AutomaticDecompression  
                var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
                //创建HttpClient(注意传入HttpClientHandler)  
                using (var http = new HttpClient(handler))
                {
                    //使用FormUrlEncodedContent做HttpContent  
                    var content = new FormUrlEncodedContent(new Dictionary<string, string>()         
                    {    {"regNO","6"},  
                         {"begin","添加zzl"},  
                         {"end", "添加动作"}  
                     });

                    //await异步等待回应  

                    var response = await http.PostAsync(url, content);
                    //确保HTTP成功状态值  
                    response.EnsureSuccessStatusCode();
                    //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)  
                    string aaa = await response.Content.ReadAsStringAsync();
                }
            }
        }
改了下,进不去方法,直接报错 {"非同步作業目前無法開始。非同步作業只有在非同步處理常式或模組或是頁面生命週期中特定事件期間中才能開始。如果執行頁面時發生此例外狀況,請確認頁面已標示為 <%@ Page Async=\"true\" %>。此例外狀況也可能表示嘗試呼叫一般在 ASP.NET 要求處理中不支援的 \"async void\" 方法。相反地,非同步方法應傳回工作而呼叫端應等候它。"}
-一个大坑 2017-06-27
  • 打赏
  • 举报
回复
引用 13 楼 hanjun0612 的回复:
[quote=引用 12 楼 happy4944 的回复:] [quote=引用 9 楼 hanjun0612 的回复:] http://blog.csdn.net/hanjun0612/article/details/60126445 http://blog.csdn.net/hanjun0612/article/details/50893719
执行到这步var response = await http.PostAsync(url, content);自动返回,也不提示成功没有[/quote] 等待一会就知道了。因为这是异步的。[/quote] 等了快一个小时,异步后面的断点一直没被触发。
-一个大坑 2017-06-27
  • 打赏
  • 举报
回复
引用 13 楼 hanjun0612 的回复:
[quote=引用 12 楼 happy4944 的回复:] [quote=引用 9 楼 hanjun0612 的回复:] http://blog.csdn.net/hanjun0612/article/details/60126445 http://blog.csdn.net/hanjun0612/article/details/50893719
执行到这步var response = await http.PostAsync(url, content);自动返回,也不提示成功没有[/quote] 等待一会就知道了。因为这是异步的。[/quote] 一直没用过异步。我var 了个接收值{Id = 12, Status = WaitingForActivation, Method = "{null}", Result = "{尚未計算}"} 返回到了页面,调试显示还在进行
加载更多回复(7)

679

社区成员

发帖
与我相关
我的任务
社区描述
智能路由器通常具有独立的操作系统,包括OpenWRT、eCos、VxWorks等,可以由用户自行安装各种应用,实现网络和设备的智能化管理。
linuxpython 技术论坛(原bbs)
社区管理员
  • 智能路由器社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧