Exemple #1
0
 protected static void CheckForBindingInPutOperations(HttpVerbs requestVerb)
 {
     if (requestVerb == HttpVerbs.PUT)
     {
         throw DataServiceException.CreateBadRequestError(System.Data.Services.Strings.BadRequest_CannotUpdateRelatedEntitiesInPut);
     }
 }
        public PartialViewResult Users(HttpVerbs? method, int? page, int? sizePage)
        {
            var model = new ModelTestApiResult();

            // if 'Get'
            if(method == HttpVerbs.Get)
            {
                // start the timer
                var timer = Stopwatch.StartNew();

                // perform the call
                List<UserV2> users;
                var response = LicenceManager.TryListUsers(out users);

                // stop the timer
                timer.Stop();
                model.ElapsedMilliseconds = timer.ElapsedMilliseconds;

                // get the content
                model.Users = users;
                // get the code
                model.ResponseBody = response.GetBodyAsString();
                // get the exception message
                model.Message = response.MessageError;
                // get the status code
                model.StatusCode = response.StatusHttp;
            }
                // if method is not supported
            else
                model.Message = "Method not supported";

            return this.PartialView("Result", model);
        }
 /// <summary>
 /// 初始化一个新的<see cref="DynamicApiActionInfo"/>实例
 /// </summary>
 /// <param name="actionName">Action 名称</param>
 /// <param name="verb">HTTP Verb</param>
 /// <param name="method">一个方法信息,随着 Action 的调用而调用</param>
 /// <param name="filters">用于 Controller Action 的动态筛选器</param>
 public DynamicApiActionInfo(string actionName, HttpVerbs verb, MethodInfo method, IFilter[] filters = null)
 {
     ActionName = actionName;
     Verb = verb;
     Method = method;
     Filters = filters ?? new IFilter[] { };
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="RESTFulActionConstraint"/> class.
        /// </summary>
        /// <param name="httpVerb">The HTTP verb.</param>
        /// <param name="requiresId">if set to <c>true</c> [requires id].</param>
        public RESTFulActionConstraint(HttpVerbs httpVerb, bool requiresId)
        {
            HttpVerbs = httpVerb;
            RequiresId = requiresId;

            verbs = ConvertToStringList(HttpVerbs);
        }
 private static void AddEntryToList(HttpVerbs verbs, HttpVerbs match, List<string> verbList, string entryText)
 {
     if ((verbs & match) != 0)
     {
         verbList.Add(entryText);
     }
 }
Exemple #6
0
 private static void RunPostExecutionFilters(IAction action, HttpVerbs httpVerb) {
     var filters = GetFilters(action, httpVerb);
     filters.ForEach(x => {
                         x.Context = action.Context;
                         x.AfterExecute();
                     });
 }
        private Method GetRestsharpMethod(HttpVerbs method)
        {
            Method result;

            switch (method)
            {
                case HttpVerbs.Get:
                    result = Method.GET;
                    break;
                case HttpVerbs.Post:
                    result = Method.POST;
                    break;
                case HttpVerbs.Put:
                    result = Method.PUT;
                    break;
                case HttpVerbs.Patch:
                    result = Method.PATCH;
                    break;
                case HttpVerbs.Delete:
                    result = Method.DELETE;
                    break;
                case HttpVerbs.Head:
                    result = Method.HEAD;
                    break;
                default:
                    result = Method.GET;
                    break;
            }

            return result;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientPreference"/> class.
 /// </summary>
 /// <param name="requestDescription">The request description.</param>
 /// <param name="verb">The request verb.</param>
 /// <param name="requestMessage">The request message.</param>
 /// <param name="effectiveMaxResponseVersion">The effective max response version for the request, which is the min of MDSV and MPV.</param>
 public ClientPreference(RequestDescription requestDescription, HttpVerbs verb, IODataRequestMessage requestMessage, Version effectiveMaxResponseVersion)
     : this(InterpretClientPreference(requestDescription, verb, requestMessage))
 {
     if (effectiveMaxResponseVersion >= VersionUtil.Version4Dot0)
     {
         this.annotationFilter = requestMessage.PreferHeader().AnnotationFilter;
     }
 }
 public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs)
 {
   this._verbs = new AcceptVerbsAttribute(verbs);
   this._validator = new ValidateAntiForgeryTokenAttribute()
   {
     Salt = Consts.AntiForgeryToken
   };
 }
		public ApiDocumentationAttribute( String url, String description = "", Type returnType = null, HttpVerbs requestType = HttpVerbs.Get, Type formBody = null )
		{
			Url = url;
			Description = description;
			ReturnType = returnType;
			RequestType = requestType;
			FormBody = formBody;
		}		
 public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt)
 {
     this._verbs = new AcceptVerbsAttribute(verbs);
     this._validator = new ValidateAntiForgeryTokenAttribute()
     {
         Salt = salt
     };
 }
Exemple #12
0
        public string DoRequest(string query, HttpVerbs method, Action<Stream> data, string contenttype)
        {

            Stream stream = DoDataRequest(query, method, data, contenttype);
            System.IO.StreamReader sr = new StreamReader(stream, Encoding.UTF8);

            return sr.ReadToEnd();
        }
 public static HtmlTag Form
     (this HtmlHelper html, string actionName, string controllerName, RouteValueDictionary routeValues,
      HttpVerbs method)
 {
     var action = UrlHelper.GenerateUrl
         (null, actionName, controllerName, routeValues, html.RouteCollection,
          html.ViewContext.RequestContext, true);
     return BuildForm(action, method);
 }
Exemple #14
0
        public string DoRequest(string query, HttpVerbs method, string data, string contenttype)
        {
            Action<Stream> a = null;
            if (!string.IsNullOrEmpty(data))
                a = (s => (new BinaryWriter(s)).Write(Encoding.UTF8.GetBytes(data)));


            return DoRequest(query, method, a, contenttype);

        }
Exemple #15
0
        internal static string[] EnumToArray(HttpVerbs verbs) {
            List<string> verbList = new List<string>();

            AddEntryToList(verbs, HttpVerbs.Get, verbList, "GET");
            AddEntryToList(verbs, HttpVerbs.Post, verbList, "POST");
            AddEntryToList(verbs, HttpVerbs.Put, verbList, "PUT");
            AddEntryToList(verbs, HttpVerbs.Delete, verbList, "DELETE");
            AddEntryToList(verbs, HttpVerbs.Head, verbList, "HEAD");

            return verbList.ToArray();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomValidateAntiForgeryTokenAttribute"/> class.
        /// </summary>
        /// <param name="verbs">The verbs.</param>
        /// <param name="salt">The salt.</param>
        public CustomValidateAntiForgeryTokenAttribute(HttpVerbs verbs, string salt)
        {
            Verbs = verbs;
            Salt = salt;

            AcceptVerbsAttribute = new AcceptVerbsAttribute(Verbs);
            Validator = new ValidateAntiForgeryTokenAttribute
            {
                Salt = Salt
            };
        }
        private static ReadOnlyCollection<string> ConvertVerbs(HttpVerbs verbs)
        {
            ReadOnlyCollection<string> verbsAsCollection;
            if (_verbsToVerbCollections.TryGetValue(verbs, out verbsAsCollection))
            {
                return verbsAsCollection;
            }

            verbsAsCollection = new ReadOnlyCollection<string>(EnumToArray(verbs));
            _verbsToVerbCollections.TryAdd(verbs, verbsAsCollection);
            return verbsAsCollection;
        }
 private void Route(string action, HttpVerbs verb)
 {
     var actionName = action.ToLowerInvariant();
     if (!_actions.ContainsKey(action))
         _actions[actionName] = new[] { verb };
     else
     {
         var verbs = _actions[actionName].ToList();
         verbs.Add(verb);
         _actions[actionName] = verbs.ToArray();
     }
 }
 public BaseAuthorizationProvider(HttpContextBase hcb)
 {
     Context = hcb;
     var rdv = ((MvcHandler)Context.CurrentHandler).RequestContext.RouteData.Values;
     Httpverb = (HttpVerbs)(Enum.Parse(typeof(HttpVerbs), Context.Request.GetHttpMethodOverride(), true)); // returns actual method if no override specified.
     // assumes specific Resources will be accessed by Id (see BaseResourceModel)
     // _id = rdv.ContainsKey("Id") ? rdv["Id"].ToString() : "";
     Controller = rdv["controller"].ToString();
     Action = rdv["action"].ToString();
     //var n = _context.User.Identity.Name;
     Init();
 }
        public static RouteData For(this RouteCollection routes, HttpVerbs verb, string url)
        {
            var httpContext = MockRepository.GenerateStub<HttpContextBase>();
            var httpRequest = MockRepository.GenerateStub<HttpRequestBase>();
            httpContext.Stub(x => x.Request).Return(httpRequest);

            httpRequest.Stub(r => r.Headers).Return(new NameValueCollection());
            httpRequest.Stub(r => r.PathInfo).Return(string.Empty);
            httpRequest.Stub(r => r.AppRelativeCurrentExecutionFilePath).Return(url);
            httpRequest.Stub(r => r.HttpMethod).Return(Enum.GetName(typeof(HttpVerbs), verb));

            return routes.GetRouteData(httpContext);
        }
 private void Route(string resource, string action, HttpVerbs verb)
 {
     var actionName = RouteSet.LowercaseActions ? action.ToLowerInvariant() : action;
     if (!_actions.ContainsKey(action))
         _actions[actionName] = new KeyValuePair<string,HttpVerbs[]>(resource, new[] { verb });
     else
     {
         var keyValue = _actions[actionName];
         var verbs = keyValue.Value.ToList();
         verbs.Add(verb);
         _actions[actionName] = new KeyValuePair<string,HttpVerbs[]>(keyValue.Key, verbs.ToArray());
     }
 }
        private async Task<HttpResponseMessage> ExecuteRequest(HttpVerbs method, Uri requestUri, HttpContent content = null)
        {
            var request = WebRequest.CreateHttp(requestUri);
            var httpResponseMessage = new HttpResponseMessage();

            request.Headers = DefaultRequestHeaders;
            request.Method = method.ToString();
            request.Accept = "*/*";

            httpResponseMessage.Request = request;

            Logger.LogWebRequest(request);
            if (content != null) Logger.LogVerbose(content.ToString());

            try
            {
                if (method == HttpVerbs.POST)
                {
                    request.ContentType = content.ContentType;

                    var requestStreamTask = Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null);
                    using (Stream stream = await requestStreamTask.ConfigureAwait(false))
                    {
                        content.WriteToStream(stream);
                    }
                }

                var responseTask = Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
                using (var response = await responseTask.ConfigureAwait(false) as HttpWebResponse)
                {
                    httpResponseMessage.SetResponseData(response);
                    Logger.LogWebResponse(response);
                }
            }
            catch (WebException we)
            {
                var response = (HttpWebResponse)we.Response;
                if (response != null)
                    httpResponseMessage.SetResponseData(response);

                Logger.Log(we);
            }
            catch (Exception e)
            {
                Logger.Log(e);
            }

            return httpResponseMessage;
        }
 private static IEnumerable<string> ConvertToStringList(HttpVerbs verb)
 {
     IList<string> list = new List<string>();
     Action<HttpVerbs> append = matching =>
     {
         if ((verb & matching) != 0)
         {
             list.Add(matching.ToString().ToUpperInvariant());
         }
     };
     foreach (HttpVerbs known in knownVerbs)
     {
         append(known);
     }
     return list;
 }
 private static HtmlTag Method(this FormTag tag, HttpVerbs method)
 {
     switch (method)
     {
         case HttpVerbs.Get:
             return tag.Method("GET");
         case HttpVerbs.Post:
             return tag.Method("POST");
         case HttpVerbs.Put:
         case HttpVerbs.Delete:
         case HttpVerbs.Head:
             return tag.Method("POST").MethodOverride(method);
     }
     throw new InvalidOperationException
         (string.Format("The {0} form method is not currently supported.", method));
 }
 // CODEREVIEW: this impleemntation kind of misses the point of HttpVerbs
 // by falling back to string comparison, consider something better
 // also, how do we keep this switch in sync?
 public static bool IsHttpMethod(this HttpRequestBase request, HttpVerbs httpMethod, bool allowOverride) {
     switch (httpMethod) {
         case HttpVerbs.Get:
             return request.IsHttpMethod("GET", allowOverride);
         case HttpVerbs.Post:
             return request.IsHttpMethod("POST", allowOverride);
         case HttpVerbs.Put:
             return request.IsHttpMethod("PUT", allowOverride);
         case HttpVerbs.Delete:
             return request.IsHttpMethod("DELETE", allowOverride);
         case HttpVerbs.Head:
             return request.IsHttpMethod("HEAD", allowOverride);
         default:
             // CODEREVIEW: does this look reasonable?
             return request.IsHttpMethod(httpMethod.ToString().ToUpperInvariant(), allowOverride);
     }
 }
        public string Request(HttpVerbs method, string endPoint, Dictionary<string,object> headers, Dictionary<string, object> parameters, Dictionary<string, object> queryParameters, string body) 
        {
            var restSharpMethod = GetRestsharpMethod(method);
            var client = new RestClient(_baseUrl);
            var request = new RestRequest(endPoint, restSharpMethod);
            client.Authenticator = _authenticator;

            //Headers
            if (headers != null)
            {
                foreach (var key in headers.Keys)
                {
                    request.AddHeader(key,
                        headers[key].GetType().ToString().StartsWith("System.Collections.Generics.List")
                            ? JsonConvert.SerializeObject(headers[key])
                            : headers[key].ToString());
                }
            }
            
            //Parameters
            if (parameters != null)
            {
                foreach (var key in parameters.Keys)
                {
                    request.AddParameter(key, parameters[key]);
                }
            }

            //QueryParameters
            if (queryParameters != null && headers != null)
            { 
                foreach (var key in queryParameters.Keys)
                {
                    request.AddQueryParameter(key,
                        headers[key].GetType().ToString().StartsWith("System.Collections.Generics.List")
                            ? JsonConvert.SerializeObject(queryParameters[key])
                            : queryParameters[key].ToString());
                }
            }

            var response = client.Execute(request);
            return response.Content;
        }
Exemple #27
0
        public Stream DoDataRequest(string query, HttpVerbs method, Action<Stream> data, string contenttype)
        {
            HttpWebRequest req = WebRequest.Create(new Uri(Url,query)) as HttpWebRequest;

            if (Credentials != null)
                req.Credentials = Credentials;

            req.Method = method.ToString();

            //req.Timeout = System.Threading.Timeout.Infinite;
            if (!string.IsNullOrEmpty(contenttype))
                req.ContentType = contenttype;

            if (data != null)
            {
                using (Stream ps = req.GetRequestStream())
                {
                    data.Invoke(ps);
                }
            }
            try
            {
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

                if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Created)
                    return resp.GetResponseStream();

                throw new RestException(resp.StatusCode, resp.StatusDescription);
            }
            catch (WebException ex)
            {
                HttpWebResponse resp = ex.Response as HttpWebResponse;
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string contents = sr.ReadToEnd();
                throw new RestException(resp.StatusCode, resp.StatusDescription);
            }


        }
Exemple #28
0
        public RemoteValidator(string errorMessage, string action, string controller, HttpVerbs httpVerb = HttpVerbs.Get, string additionalFields = "")
            : base(errorMessage)
        {
            var httpContext = HttpContext.Current;

            if (httpContext == null)
            {
                var request = new HttpRequest("/", "http://ubasolutions.com", "");
                var response = new HttpResponse(new StringWriter());
                httpContext = new HttpContext(request, response);
            }

            var httpContextBase = new HttpContextWrapper(httpContext);
            var routeData = new RouteData();
            var requestContext = new RequestContext(httpContextBase, routeData);

            var helper = new UrlHelper(requestContext);

            Url = helper.Action(action, controller);
            HttpMethod = httpVerb.ToString();
            AdditionalFields = additionalFields;
        }
        //"{PropertyName} must be unique."
        public IsUniquePropertyValidator(IPropertyValidatorService service, string errorMessage,
                         string action,
                         string controller,
                         HttpVerbs HttpVerb = HttpVerbs.Get,
                         string additionalFields = "")
            : base(errorMessage)
        {
            this._service = service;
            var httpContext = HttpContext.Current;

            if (httpContext != null)
            {
                var httpContextBase = new HttpContextWrapper(httpContext);
                var routeData       = new RouteData();
                var requestContext  = new RequestContext(httpContextBase, routeData);

                var helper       = new UrlHelper(requestContext);
                Url              = helper.Action(action, controller);
                HttpMethod       = HttpVerb.ToString();
                AdditionalFields = additionalFields;
            }
        }
        public RequestResult ProcessRequest(string url, HttpVerbs httpVerb, NameValueCollection formValues, NameValueCollection headers)
        {
            if (url == null) throw new ArgumentNullException("url");

            // Fix up URLs that incorrectly start with / or ~/
            if (url.StartsWith("~/"))
                url = url.Substring(2);
            else if(url.StartsWith("/"))
                url = url.Substring(1);

            // Parse out the querystring if provided
            string query = "";
            int querySeparatorIndex = url.IndexOf("?");
            if (querySeparatorIndex >= 0) {
                query = url.Substring(querySeparatorIndex + 1);
                url = url.Substring(0, querySeparatorIndex);
            }                

            // Perform the request
            LastRequestData.Reset();
            var output = new StringWriter();
            string httpVerbName = httpVerb.ToString().ToLower();
            var workerRequest = new SimulatedWorkerRequest(url, query, output, Cookies, httpVerbName, formValues, headers);
            HttpRuntime.ProcessRequest(workerRequest);

            // Capture the output
            AddAnyNewCookiesToCookieCollection();
            Session = LastRequestData.HttpSessionState;
            return new RequestResult
            {
                ResponseText = output.ToString(),
                ActionExecutedContext = LastRequestData.ActionExecutedContext,
                ResultExecutedContext = LastRequestData.ResultExecutedContext,
                Response = LastRequestData.Response,
            };
        }
Exemple #31
0
 public static bool IsHttpMethod(this HttpRequestBase request, HttpVerbs httpMethod)
 {
     return(request.IsHttpMethod(httpMethod, false));
 }
Exemple #32
0
 public static RouteData WithMethod(this string url, HttpVerbs verb)
 {
     return(WithMethod(url, verb.ToString("g")));
 }
Exemple #33
0
 /// <summary>
 /// Asserts that the route matches the expression specified based on the incoming HttpMethod and FormMethod for Simply Restful routing.  Checks controller, action, and any method arguments
 /// into the action as route values.
 /// </summary>
 /// <param name="relativeUrl">The relative URL.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="formMethod">The form method.</param>
 /// <returns></returns>
 public static RouteData WithMethod(this string relativeUrl, HttpVerbs httpMethod, HttpVerbs formMethod)
 {
     return(relativeUrl.Route(httpMethod, formMethod));
 }
Exemple #34
0
 public static RouteData WithMethod(this string url, HttpVerbs verb)
 {
     return(AsRoute(url, verb));
 }
 public ControllerContextBuilder <TController> WithRoute(string relativeUrl, HttpVerbs method = HttpVerbs.Get)
 {
     requestPath   = relativeUrl;
     requestMethod = method;
     return(this);
 }
 /// <summary>
 /// Initialises a new instance of the <see cref="ValueComputationFuncModel"/> class.
 /// </summary>
 /// <param name="endpointTriggers">The HTTP method verbs that will trigger the computation.</param>
 public ValueComputationFuncModel(HttpVerbs endpointTriggers)
 {
     EndpointTriggers = endpointTriggers;
 }
 /// <summary>
 /// Make a request to the app, with custom verb, headers and body
 /// </summary>
 public RequestResult Request(string url, HttpVerbs httpVerb, NameValueCollection headers, byte[] bodyData)
 {
     return(ProcessRequest(url, httpVerb, bodyData, headers));
 }
 /// <summary>
 /// Specifies the HTTP verb of the request.
 /// </summary>
 /// <param name="verb">The HTTP verb</param>
 public CrudOperationBuilder Type(HttpVerbs verb)
 {
     operation.Type = verb.ToString().ToUpperInvariant();
     return(this);
 }
Exemple #39
0
        /// <summary>
        ///     Returns the corresponding route for the URL.  Returns null if no route was found.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="httpMethod">The HTTP method.</param>
        /// <returns></returns>
        public static RouteData AsRoute(this string url, HttpVerbs httpMethod = HttpVerbs.Get)
        {
            var context = GetHttpContext(url, httpMethod);

            return(RouteTable.Routes.GetRouteData(context));
        }
Exemple #40
0
 public AcceptVerbsAttribute(HttpVerbs verbs)
     : this(EnumToArray(verbs))
 {
 }
Exemple #41
0
 public ApiDocumentationAttribute(string url, string summaryDescription = "", string notes = "", Type returnType = null, HttpVerbs requestType = HttpVerbs.Get, Type formBody = null)
 {
     Url = url;
     SummaryDescription = summaryDescription;
     Notes       = notes;
     ReturnType  = returnType;
     RequestType = requestType;
     FormBody    = formBody;
 }
 /// <summary>
 /// Basic version of the configuration. No ignored actions and no specific salt.
 /// </summary>
 /// <param name="verbs">HTTP request type for which anti forgery checks will be performed. Typically a POST.</param>
 public ValidateAntiForgeryTokenOnControllerAttribute(HttpVerbs verbs)
     : this(verbs, (string[])null)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseRouteAttribute"/> class.
 /// </summary>
 /// <param name="verb">The verb.</param>
 /// <param name="route">The route.</param>
 /// <exception cref="ArgumentNullException"><paramref name="route"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentException">
 /// <para><paramref name="route"/> is empty.</para>
 /// <para>- or -</para>
 /// <para><paramref name="route"/> does not start with a slash (<c>/</c>) character.</para>
 /// <para>- or -</para>
 /// <para><paramref name="route"/> does not comply with route syntax.</para>
 /// </exception>
 /// <seealso cref="Routing.Route.IsValid"/>
 public BaseRouteAttribute(HttpVerbs verb, string route)
     : base(verb, route, true)
 {
 }
        /// <summary>
        /// Executes the requested method.
        /// to the proper types for execution.
        /// </summary>
        /// <param name="Method"></param>
        /// <param name="methodParameters">An array of the string json parameters to </param>
        /// <param name="target">The object to call the method on</param>
        /// <param name="parameters">An array of json Strings that make up the parameters for the method call. This value can be null in which case parms are parsed out of GET QueryString or POST values</param>
        /// <param name="callbackMethodAttribute">An optional instance of an CallbackAttribute that is set by this method</param>
        /// <returns>the result of the method execution</returns>
        internal object ExecuteMethod(string method, object target, string[] parameters,
                                      CallbackMethodParameterType paramType,
                                      ref CallbackMethodAttribute callbackMethodAttribute)
        {
            HttpRequest  Request  = HttpContext.Current.Request;
            HttpResponse Response = HttpContext.Current.Response;

            object Result = null;

            // Stores parsed parameters (from string JSON or QUeryString Values)
            object[] adjustedParms = null;

            Type       PageType = target.GetType();
            MethodInfo MI       = PageType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            if (MI == null)
            {
                throw new InvalidOperationException();
            }

            object[] methods = MI.GetCustomAttributes(typeof(CallbackMethodAttribute), false);
            if (methods.Length < 1)
            {
                throw new InvalidOperationException();
            }

            if (callbackMethodAttribute != null)
            {
                callbackMethodAttribute = methods[0] as CallbackMethodAttribute;
            }

            // Check for supported HTTP Verbs
            if (callbackMethodAttribute.AllowedHttpVerbs != HttpVerbs.All &&
                !string.IsNullOrEmpty(Request.HttpMethod))
            {
                HttpVerbs val = HttpVerbs.None;
                Enum.TryParse <HttpVerbs>(Request.HttpMethod, out val);
                if (val == HttpVerbs.None || !callbackMethodAttribute.AllowedHttpVerbs.HasFlag(val))
                {
                    Response.StatusCode        = (int)HttpStatusCode.MethodNotAllowed;
                    Response.StatusDescription = string.Format("NotAllowedMethodExpectsVerb");
                    throw new UnauthorizedAccessException(Response.StatusDescription);
                }
            }

            ParameterInfo[] parms = MI.GetParameters();

            JSONSerializer serializer = new JSONSerializer();

            RouteData routeData = null;

            if (target is CallbackHandler)
            {
                routeData = ((CallbackHandler)target).RouteData;
            }

            int parmCounter = 0;

            adjustedParms = new object[parms.Length];
            foreach (ParameterInfo parameter in parms)
            {
                // Retrieve parameters out of QueryString or POST buffer
                if (parameters == null)
                {
                    // look for parameters in the route
                    if (routeData != null)
                    {
                        string parmString = routeData.Values[parameter.Name] as string;
                        adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);
                    }
                    // GET parameter are parsed as plain string values - no JSON encoding
                    else if (HttpContext.Current.Request.HttpMethod == "GET")
                    {
                        // Look up the parameter by name
                        string parmString = Request.QueryString[parameter.Name];
                        adjustedParms[parmCounter] = ReflectionUtils.StringToTypedValue(parmString, parameter.ParameterType);
                    }
                    // POST parameters are treated as methodParameters that are JSON encoded
                    else
                    if (paramType == CallbackMethodParameterType.Json)
                    {
                        //string newVariable = methodParameters.GetValue(parmCounter) as string;
                        adjustedParms[parmCounter] = serializer.Deserialize(Request.Params["parm" + (parmCounter + 1).ToString()], parameter.ParameterType);
                    }
                    else
                    {
                        adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(
                            Request.Params["parm" + (parmCounter + 1).ToString()],
                            parameter.ParameterType);
                    }
                }
                else
                if (paramType == CallbackMethodParameterType.Json)
                {
                    adjustedParms[parmCounter] = serializer.Deserialize(parameters[parmCounter], parameter.ParameterType);
                }
                else
                {
                    adjustedParms[parmCounter] = SerializationUtils.DeSerializeObject(parameters[parmCounter], parameter.ParameterType);
                }

                parmCounter++;
            }

            Result = MI.Invoke(target, adjustedParms);

            return(Result);
        }
Exemple #45
0
 /// <summary>
 /// Associates a HTTP method and a route to a synchronous handler.
 /// </summary>
 /// <param name="verb">A <see cref="HttpVerbs"/> constant representing the HTTP method
 /// to associate with <paramref name="handler"/>, or <see cref="HttpVerbs.Any"/>
 /// if <paramref name="handler"/> can handle all HTTP methods.</param>
 /// <param name="route">The route to match URL paths against.</param>
 /// <param name="handler">A callback used to handle matching contexts.</param>
 /// <exception cref="ArgumentNullException">
 /// <para><paramref name="route"/> is <see langword="null"/>.</para>
 /// <para>- or -</para>
 /// <para><paramref name="handler"/> is <see langword="null"/>.</para>
 /// </exception>
 /// <exception cref="FormatException"><paramref name="route"/> is not a valid route.</exception>
 public void Add(HttpVerbs verb, string route, SyncRouteHandlerCallback handler)
 => AddHandler(verb, route, handler);
Exemple #46
0
        /// <summary>
        ///     Returns the corresponding named route.  Returns null if no route was found.
        /// </summary>
        /// <param name="name">The route name.</param>
        /// <param name="httpMethod">The HTTP method.</param>
        /// <returns>RouteData for the named route; null if no matching route was found.</returns>
        public static RouteData AsNamedRoute(this string name, HttpVerbs httpMethod = HttpVerbs.Get)
        {
            var context = GetHttpContext(name, httpMethod);

            return(RouteTable.Routes[name].IfExists(route => route.GetRouteData(context)));
        }
 public RouteAttribute(string url, HttpVerbs verbs, RoutePriority priority)
     : this(url, "", verbs, priority)
 {
 }
Exemple #48
0
 public void Add(HttpVerbs verb)
 {
     this.allowedVerbs.Add(verb.ToString());
 }
 private RequestResult ProcessRequest(string url, HttpVerbs httpVerb = HttpVerbs.Get, NameValueCollection formValues = null)
 {
     return(ProcessRequest(url, httpVerb, formValues, null));
 }
 private RequestResult ProcessRequest(string url, HttpVerbs httpVerb = HttpVerbs.Get, NameValueCollection formValues = null)
 {
     return(ProcessRequest(url, httpVerb, NameValueCollectionConversions.SerialiseFormData(formValues), null));
 }
 public RouteAttribute(string url, HttpVerbs verbs)
     : this(url, "", verbs, RoutePriority.Default)
 {
 }
Exemple #52
0
 /// <summary>
 /// Associates a HTTP method and a route to a synchronous handler.
 /// </summary>
 /// <param name="verb">A <see cref="HttpVerbs"/> constant representing the HTTP method
 /// to associate with <paramref name="handler"/>, or <see cref="HttpVerbs.Any"/>
 /// if <paramref name="handler"/> can handle all HTTP methods.</param>
 /// <param name="matcher">The <see cref="RouteMatcher"/> used to match URL paths.</param>
 /// <param name="handler">A callback used to handle matching contexts.</param>
 /// <exception cref="ArgumentNullException">
 /// <para><paramref name="matcher"/> is <see langword="null"/>.</para>
 /// <para>- or -</para>
 /// <para><paramref name="handler"/> is <see langword="null"/>.</para>
 /// </exception>
 public void Add(HttpVerbs verb, RouteMatcher matcher, SyncRouteHandlerCallback handler)
 => AddHandler(verb, matcher, handler);
Exemple #53
0
 /// <summary>
 ///     Asserts that the route matches the expression specified based on the incoming HttpMethod and FormMethod for Simply
 ///     Restful routing.  Checks controller, action, and any method arguments
 ///     into the action as route values.
 /// </summary>
 /// <param name="url">The relative URL.</param>
 /// <param name="httpMethod">The HTTP method.</param>
 /// <param name="formMethod">The form method.</param>
 /// <returns></returns>
 public static RouteData WithMethod(this string url, HttpVerbs httpMethod, HttpVerbs formMethod)
 {
     return(url.AsRoute(httpMethod, formMethod));
 }
Exemple #54
0
        /// <summary>
        /// Submits the multipart form.
        /// </summary>
        /// <returns>The multipart form.</returns>
        /// <param name="uri">URI.</param>
        /// <param name="verb">Verb.</param>
        /// <param name="userAgent">User agent.</param>
        /// <param name="encoding">Encoding.</param>
        /// <param name="uploadFile">Upload file.</param>
        /// <param name="headers">Headers.</param>
        /// <param name="parameters">Parameters.</param>
        /// <param name="username">Username.</param>
        /// <param name="password">Password.</param>
        /// <param name="accept">Accept.</param>
        /// <param name="contentType">Content type.</param>
        /// <param name="cookieContainer">Cookie container.</param>
        /// <typeparam name="TSuccess">The 1st type parameter.</typeparam>
        /// <typeparam name="TError">The 2nd type parameter.</typeparam>
        public static RequestResponseSummary <TSuccess, TError> SubmitMultipartForm <TSuccess, TError>(
            Uri uri,
            HttpVerbs verb,
            string userAgent,
            Encoding encoding               = null,
            string uploadFile               = null,
            List <Header> headers           = null,
            List <FormParameter> parameters = null,
            string username    = null,
            string password    = null,
            string accept      = null,
            string contentType = "multipart/form-data",
            CookieContainer cookieContainer = null
            )
        {
            var method  = verb.ToString();
            var summary = new RequestResponseSummary <TSuccess, TError>();

            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }

                var httpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
                if (httpWebRequest == null)
                {
                    throw new NullReferenceException("request is not a http request");
                }

                string formDataBoundary = "--" + DateTime.Now.ToString("ssfff");
                contentType = string.Format("{0}; boundary={1}", contentType, formDataBoundary);

                ManageHeaders(
                    httpWebRequest: httpWebRequest,
                    method: method,
                    headers: headers,
                    username: username,
                    password: password,
                    accept: accept,
                    contentType: contentType,
                    userAgent: userAgent,
                    cookieContainer: cookieContainer
                    );

                BuildMultiPartPayload(
                    encoding: encoding,
                    parameters: parameters,
                    contentType: contentType,
                    request: httpWebRequest,
                    formDataBoundary: formDataBoundary);

                SubmitRequestDispose <TSuccess, TError>(
                    summary: ref summary,
                    httpWebRequest: httpWebRequest);


                return(summary);
            }
            catch (WebException ex)
            {
                HandleWebException <TSuccess, TError>(
                    summary: ref summary,
                    url: uri.ToString(),
                    ex: ex);
                return(summary);
            }
            catch (Exception ex)
            {
                summary.SerializedResponse = ex.Message;
                summary.Status             = 0;
                summary.UnhandledError     = ex.Message;
                return(summary);
            }
        }
Exemple #55
0
 public bool Contains(HttpVerbs verb)
 {
     return(this.Contains(verb.ToString()));
 }
Exemple #56
0
        /// <summary>
        /// Executes the rest method.
        /// </summary>
        /// <returns>The rest method.</returns>
        /// <param name="uri">URI.</param>
        /// <param name="verb">Verb.</param>
        /// <param name="userAgent">User agent.</param>
        /// <param name="payload">Payload.</param>
        /// <param name="serializedPayload">Serialized payload.</param>
        /// <param name="parameters">Parameters.</param>
        /// <param name="headers">Headers.</param>
        /// <param name="username">Username.</param>
        /// <param name="password">Password.</param>
        /// <param name="accept">Accept.</param>
        /// <param name="cookieContainer">Cookie container.</param>
        /// <param name="contentType">Content type.</param>
        /// <typeparam name="TSuccess">The 1st type parameter.</typeparam>
        /// <typeparam name="TError">The 2nd type parameter.</typeparam>
        public static RequestResponseSummary <TSuccess, TError> ExecuteRestMethod <TSuccess, TError>(
            Uri uri,
            HttpVerbs verb,
            string userAgent,
            object payload                  = null,
            string serializedPayload        = null,
            List <FormParameter> parameters = null,
            List <Header> headers           = null,
            string username                 = null,
            string password                 = null,
            string accept = null,
            CookieContainer cookieContainer = null,
            string contentType = "application/json"

            )
        {
            string url    = uri.ToString();
            string method = verb.ToString();

            if (!acceptedMethods.Contains(method))
            {
                throw new ArgumentException(method + " is not currently supported.", method);
            }

            if (payload != null && !string.IsNullOrEmpty(serializedPayload) && parameters != null)
            {
                throw new ArgumentOutOfRangeException("payload, serializedPayload, and pameters are mutually exclusive.");
            }

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }

            var summary = new RequestResponseSummary <TSuccess, TError>();

            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

                ManageHeaders(
                    httpWebRequest: httpWebRequest,
                    method: method,
                    headers: headers,
                    username: username,
                    password: password,
                    accept: accept,
                    contentType: contentType,
                    userAgent: userAgent,
                    cookieContainer: cookieContainer
                    );

                BuildPayload(payload, serializedPayload, parameters, httpWebRequest, ref summary);

                SubmitResponseUsing <TSuccess, TError>(ref summary, httpWebRequest);

                return(summary);
            }
            catch (WebException ex)
            {
                HandleWebException <TSuccess, TError>(
                    summary: ref summary,
                    url: url,
                    ex: ex);
                return(summary);
            }
            catch (Exception ex)
            {
                summary.Results        = default(TSuccess);
                summary.UnhandledError = ex.Message;
                summary.Status         = 0;
                return(summary);
            }
        }
Exemple #57
0
        public async Task <IEnumerable <CredentialModel> > ResolveAsync(Context context, HttpVerbs httpVerb,
                                                                        IResolveUrls routeResolver, IModifyResponse responseModifier)
        {
            throw new NotImplementedException();
            //    IBusinessSocialIdentity socialIdentity;
            //    var socialIdenties = new List<IBusinessSocialIdentity>();

            //    Go find the parent that this belongs to and make sure the parent exists.
            //    var userIdentity = await context.FindUserIdentityByIdAsync(UserIdentityId);
            //    if (userIdentity == null)
            //        throw this.PreconditionViewModelEntityNotFound();

            //    if (HttpVerbs.Get == httpVerb)
            //    {
            //        if (default(Guid) == Id)
            //        {
            //            socialIdenties.AddRange(await userIdentity.SocialIdentityAsync());
            //        }
            //        else
            //        {
            //            socialIdentity = await userIdentity.FindSocialIdentityByIdAsync(Id);
            //            if (null != socialIdentity)
            //            {
            //                socialIdenties.Add(socialIdentity);
            //            }
            //        }
            //        if (!socialIdenties.Any()) throw this.PreconditionViewModelEntityNotFound();

            //        var tasks = socialIdenties.Select(t => ToViewModelAsync(t, urlHelper, requestContext));
            //        return await Task.WhenAll(tasks);
            //    }

            //    socialIdentity = await userIdentity.FindSocialIdentityByIdAsync(Id);
            //    if (HttpVerbs.Post == httpVerb)
            //    {
            //        if (null != socialIdentity)
            //        {
            //            throw this.PreconditionViewModelEntityAlreadyExists();
            //        }

            //        await userIdentity.CreateSocialIdentityAsync(this.Id, this.AppId, this.Type, this.Method, this.UserId, this.Provider, this.Token);

            //        requestContext.SetResponseCode(HttpStatusCode.Created);
            //        requestContext.AddLocationHeader(requestContext.GetEndPointUrl(urlHelper, "SocialIdentity", Id));
            //        return new SocialIdentityModel[] { };

            //    }

            //    if (HttpVerbs.Put == httpVerb)
            //    {
            //        if (null == socialIdentity)
            //        {
            //            throw this.PreconditionViewModelEntityNotFound();
            //        }

            //        await socialIdentity.UpdateToken(this.Token);

            //        requestContext.SetResponseCode(HttpStatusCode.NoContent);
            //        requestContext.AddLocationHeader(requestContext.GetEndPointUrl(urlHelper, "SocialIdentity", Id));
            //        return new SocialIdentityModel[] { };
            //    }
        }
 /// <summary>
 /// Allows to pass 2 actions to be ignored.
 /// </summary>
 /// <param name="verbs">HTTP request type for which anti forgery checks will be performed. Typically a POST.</param>
 public ValidateAntiForgeryTokenOnControllerAttribute(HttpVerbs verbs, string actionToNotValidate1, string actionToNotValidate2)
     : this(verbs, new [] { actionToNotValidate1, actionToNotValidate2 })
 {
 }
 public bool HasEndpointTrigger(HttpVerbs flag) => EndpointTriggers.HasFlag(flag);
Exemple #60
0
        public void AllActionsHaveAntiForgeryTokenIfNotGet()
        {
            // Arrange

            // If an action only supports these verbs, it doesn't need the anti-forgery token attribute.
            var verbExceptions = new HttpVerbs[]
            {
                HttpVerbs.Get,
                HttpVerbs.Head
            };

            // These actions cannot have the AntiForgery token attribute.
            // For example: API methods intended to be called by clients.
            var exceptions = new ControllerActionRuleException[]
            {
                new ControllerActionRuleException(typeof(ApiController), nameof(ApiController.CreatePackagePut)),
                new ControllerActionRuleException(typeof(ApiController), nameof(ApiController.CreateSymbolPackagePutAsync)),
                new ControllerActionRuleException(typeof(ApiController), nameof(ApiController.CreatePackagePost)),
                new ControllerActionRuleException(typeof(ApiController), nameof(ApiController.CreatePackageVerificationKeyAsync)),
                new ControllerActionRuleException(typeof(ApiController), nameof(ApiController.DeletePackage)),
                new ControllerActionRuleException(typeof(ApiController), nameof(ApiController.PublishPackage)),
                new ControllerActionRuleException(typeof(ApiController), nameof(ApiController.DeprecatePackage)),
            };

            // Act
            var assembly = Assembly.GetAssembly(typeof(AppController));

            var actions = GetAllActions(exceptions)
                          // Filter out methods that only support verbs that are exceptions.
                          .Where(m =>
            {
                var attributes = m.GetCustomAttributes()
                                 .Where(a => typeof(ActionMethodSelectorAttribute)
                                        .IsAssignableFrom(a.GetType()));

                // Non-actions cannot be requested via HTTP.
                if (attributes.Any(a => a.GetType() == typeof(NonActionAttribute)))
                {
                    _output.WriteLine($"{DisplayMethodName(m)} - non-action");
                    return(false);
                }

                var isGetOrHead = attributes
                                  .All(a =>
                                       a.GetType() == typeof(HttpGetAttribute) ||
                                       a.GetType() == typeof(HttpHeadAttribute) ||
                                       (a.GetType() == typeof(AcceptVerbsAttribute) &&
                                        (a as AcceptVerbsAttribute).Verbs.All(v =>
                                                                              verbExceptions.Any(ve => v.Equals(ve.ToString(), StringComparison.InvariantCultureIgnoreCase)))));

                if (isGetOrHead)
                {
                    _output.WriteLine($"{DisplayMethodName(m)} - GET or HEAD");
                }

                return(!isGetOrHead);
            })
                          .Select(m =>
            {
                _output.WriteLine($"{DisplayMethodName(m)} - to be verified");
                return(m);
            });

            // Assert
            var actionsMissingAntiForgeryToken = actions
                                                 .Where(m => !(m.GetCustomAttributes().Any(a => a.GetType() == typeof(ValidateAntiForgeryTokenAttribute))));

            Assert.Empty(actionsMissingAntiForgeryToken);
        }