ASP.NET MVC - Using cURL or similar to perform requests in application

前端 未结 4 1943
一整个雨季
一整个雨季 2021-02-01 11:06

I\'m building an application in ASP.NET MVC (using C#) and I would like to know how I can perform calls like curl http://www.mywebsite.com/clients_list.xml inside my controller

4条回答
  •  既然无缘
    2021-02-01 11:52

    This is the single line of code I use for calls to a RESTful API that returns JSON.

    return ((dynamic) JsonConvert.DeserializeObject(
            new WebClient().DownloadString(
                GetUri(surveyId))
        )).data;
    

    Notes

    • The Uri is generated off stage using the surveyId and credentials
    • The 'data' property is part of the de-serialized JSON object returned by the SurveyGizmo API

    The Complete Service

    public static class SurveyGizmoService
    {
        public static string UserName { get { return WebConfigurationManager.AppSettings["SurveyGizmo.UserName"]; } }
        public static string Password { get { return WebConfigurationManager.AppSettings["SurveyGizmo.Password"]; } }
        public static string ApiUri { get { return WebConfigurationManager.AppSettings["SurveyGizmo.ApiUri"]; } }
        public static string SurveyId { get { return WebConfigurationManager.AppSettings["SurveyGizmo.Survey"]; } }
    
        public static dynamic GetSurvey(string surveyId = null)
        {
            return ((dynamic) JsonConvert.DeserializeObject(
                    new WebClient().DownloadString(
                        GetUri(surveyId))
                )).data;
        }
    
        private static Uri GetUri(string surveyId = null)
        {
            if (surveyId == null) surveyId = SurveyId;
            return new UriBuilder(ApiUri)
                    {
                            Path = "/head/survey/" + surveyId,
                            Query = String.Format("user:pass={0}:{1}", UserName, Password)
                    }.Uri;
        }
    }
    

提交回复
热议问题