首页 新闻 赞助 找找看

用restful api 如何在.Net后台调用get,post,put delete?

0
[已解决问题] 解决于 2016-07-27 10:00

正在学习node.js,想具体了解restful api,在后台里想调用get, post ,put ,delete

PS:前端的请求操作已经有资源了,但是后端调用的资料不全面,希望好心的园友帮忙最好有一个demo,我的理解力差,有demo我会更好理解些,现在理论知识已经get了,但是写代码就是写不来,再次希望懂的园友能给我全面的代码demo,谢谢~~

小宇宙呀的主页 小宇宙呀 | 菜鸟二级 | 园豆:207
提问于:2016-07-18 16:04
< >
分享
最佳答案
0
public class UserService : IUserService
    {
        private ICommonService _commonService;

        public UserService(ICommonService commonService)
        {
            _commonService = commonService;
        }

        public List<UserDto> GetUserList()
        {
            var client = new HttpClient().CreateClient(_commonService.GetFullUri("api/users"));
            return client.GetMethod<List<UserDto>>();
        }

        public UserDto GetUserById(int userId)
        {
            var client = new HttpClient().CreateClient(_commonService.GetFullUri("api/users/{userId}"));
            client.AddUriParameter("userId", userId.ToString());
            return client.GetMethod<UserDto>();
        }

        public List<UserDto> GetUserListByName(string name)
        {
            var client = new HttpClient().CreateClient(_commonService.GetFullUri("api/users/querybyname"));
            client.AddQueryParameter("name", name);
            return client.GetMethod<List<UserDto>>();
        }

        public string AddUserList(List<UserDto> userList)
        {
            var client = new HttpClient().CreateClient(_commonService.GetFullUri("api/users"));
            return client.PostMethod(userList);
        }

        public string EditUser(int userId, UserDto userDto)
        {
            var client = new HttpClient().CreateClient(_commonService.GetFullUri("api/users/{userId}"));
            client.AddUriParameter("userId", userId.ToString());
            return client.PutMethod(userDto);
        }

        public string DeleteUser(int userId)
        {
            var client = new HttpClient().CreateClient(_commonService.GetFullUri("api/users/{userId}"));
            client.AddUriParameter("userId", userId.ToString());
            return client.DeleteMethod();
        }
    }
public class CommonService : ICommonService
    {
        public string GetFullUri(string uri)
        {
            var baseUri = GetConfigObject<AppSettings>("AppSettings").WebApiBasePath;
            return string.Format("{0}/{1}", baseUri.Trim('/'), uri.Trim('/'));
        }

        public T GetConfigObject<T>(string sectionName)
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables().Build();
            return configuration.Get<T>(sectionName);
        }
    }

这是我以前写着玩的,用的System.Net.Http;

public static class RestApiService
    {
        public static T GetMethod<T>(this HttpClient client)
        {
            if (typeof(T) == typeof(string))
            {
                throw new Exception("Please use complex object as a generic. Please don't use string.");
            }
            return GetAsyncObject<T>(client).Result;
        }

        public static string GetMethod(this HttpClient client)
        {
            return GetAsync(client).Result;
        }

        public static T PostMethod<T>(this HttpClient client, object param)
        {
            if (typeof(T) == typeof(string))
            {
                throw new Exception("Please use complex object as a generic. Please don't use string.");
            }
            return PostAsync<T>(client, param).Result;
        }

        public static string PostMethod(this HttpClient client, object param)
        {
            return PostAsync(client, param).Result;
        }

        public static T PutMethod<T>(this HttpClient client, object param)
        {
            if (typeof(T) == typeof(string))
            {
                throw new Exception("Please use complex object as a generic. Please don't use string.");
            }
            return PutAsync<T>(client, param).Result;
        }

        public static string PutMethod(this HttpClient client, object param)
        {
            return PutAsync(client, param).Result;
        }

        public static T DeleteMethod<T>(this HttpClient client)
        {
            if (typeof(T) == typeof(string))
            {
                throw new Exception("Please use complex object as a generic. Please don't use string.");
            }
            return DeleteAsync<T>(client).Result;
        }

        public static string DeleteMethod(this HttpClient client)
        {
            return DeleteAsync(client).Result;
        }

        public static HttpClient CreateClient(this HttpClient client, string requestUri)
        {
            client.BaseAddress = new Uri(requestUri);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            return client;
        }

        public static HttpClient AddUriParameter(this HttpClient client, string paramName, string paramValue)
        {
            var uriStr = WebUtility.UrlDecode(client.BaseAddress.AbsoluteUri.ToLower());
            var replaceParamName = string.Format("{0}{1}{2}", "{", paramName.ToLower(), "}");
            uriStr = uriStr.Replace(replaceParamName, paramValue);
            client.BaseAddress = new Uri(uriStr);
            return client;
        }

        public static HttpClient AddQueryParameter(this HttpClient client, string paramName, string paramValue)
        {
            var uriStr = WebUtility.UrlDecode(client.BaseAddress.AbsoluteUri.ToLower());
            var query = client.BaseAddress.Query.ToLower();
            if (uriStr.Contains("{" + paramName.ToLower() + "}"))
            {
                uriStr = uriStr.Replace("{" + paramName.ToLower() + "}", paramValue);
            }
            else if (query.Length > 0)
            {
                uriStr = string.Format("{0}&{1}={2}", uriStr, paramName, paramValue);
            }
            else
            {
                uriStr = string.Format("{0}?{1}={2}", uriStr, paramName, paramValue);
            }
            client.BaseAddress = new Uri(uriStr);
            return client;
        }

        private static async Task<T> GetAsyncObject<T>(HttpClient client)
        {
            var response = await client.GetAsync(client.BaseAddress);
            if (response.IsSuccessStatusCode)
            {
                var jsonStr = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }

        private static async Task<T> PostAsync<T>(HttpClient client, object param)
        {
            if (param == null)
            {
                throw new Exception("Please don't post null object.");
            }
            HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8,
                "application/json");
            HttpResponseMessage response = await client.PostAsync(client.BaseAddress, contentPost);
            if (response.IsSuccessStatusCode)
            {
                var jsonStr = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }

        private static async Task<T> DeleteAsync<T>(HttpClient client)
        {
            HttpResponseMessage response = await client.DeleteAsync(client.BaseAddress);
            if (response.IsSuccessStatusCode)
            {
                var jsonStr = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }

        private static async Task<string> DeleteAsync(HttpClient client)
        {
            HttpResponseMessage response = await client.DeleteAsync(client.BaseAddress);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }

        private static async Task<T> PutAsync<T>(HttpClient client, object param)
        {
            if (param == null)
            {
                throw new Exception("Please don't put null object.");
            }
            HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8,
                "application/json");
            HttpResponseMessage response = await client.PutAsync(client.BaseAddress, contentPost);
            if (response.IsSuccessStatusCode)
            {
                var jsonStr = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }

        private static async Task<string> PutAsync(HttpClient client, object param)
        {
            if (param == null)
            {
                throw new Exception("Please don't put null object.");
            }
            HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8,
                "application/json");
            HttpResponseMessage response = await client.PutAsync(client.BaseAddress, contentPost);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }

        private static async Task<string> PostAsync(HttpClient client, object param)
        {
            if (param == null)
            {
                throw new Exception("Please don't post null object.");
            }
            HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(param), Encoding.UTF8,
               "application/json");
            HttpResponseMessage response = await client.PostAsync(client.BaseAddress, contentPost);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }

        private static async Task<string> GetAsync(HttpClient client)
        {
            var response = await client.GetAsync(client.BaseAddress);
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            throw new Exception(response.ReasonPhrase + ":" + response.RequestMessage);
        }
    }

之前自己写着玩的,现在有很多别人封装好了的,网上去搜下,例如restsharp之类的

奖励园豆:5
Buthcer | 菜鸟二级 |园豆:238 | 2016-07-18 17:47
其他回答(1)
0

webapiclient百度上搜索下吧.很容易的

吴瑞祥 | 园豆:29449 (高人七级) | 2016-07-18 17:15

恩恩,好的,现在知道具体的查找的方向了,非常感谢!到时候有不懂的可以再问你吗?

支持(0) 反对(0) 小宇宙呀 | 园豆:207 (菜鸟二级) | 2016-07-18 19:48
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册