MethodNotAllowed (405)

The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
4010
public static function MethodNotAllowed($body = NULL, \Exception $previous = NULL) {
    return self::code(405, $body, $previous);
  }
192426
def request(self, uri, method, *args, **kwargs):
        
        if self.timeout:
            kwargs["timeout"] = self.timeout
        kwargs["verify"] = self.verify_ssl
        kwargs.setdefault("headers", kwargs.get("headers", {}))
        kwargs["headers"]["User-Agent"] = self.user_agent
        kwargs["headers"]["Accept"] = "application/json"
        if ("body" in kwargs) or ("data" in kwargs):
            if "Content-Type" not in kwargs["headers"]:
                kwargs["headers"]["Content-Type"] = "application/json"
            elif kwargs["headers"]["Content-Type"] is None:
                del kwargs["headers"]["Content-Type"]
        # Allow subclasses to add their own headers
        self._add_custom_headers(kwargs["headers"])
        resp, body = pyrax.http.request(method, uri, *args, **kwargs)
        if resp.status_code >= 400:
            raise exc.from_response(resp, body)
        return resp, body
620109
function request (suppliedOptions,data,next) 
{
    var options = makeOptions(suppliedOptions);
    switch (options.method ? options.method.toUpperCase() : "BADMETHOD") {
        case "PUT":
        case "POST":
                    var dataString = JSON.stringify(data);
                    options.headers['Content-Length'] = dataString.length;
                    var req = https.request(options,requestDone);
                    req.end(dataString);
                    break;
        case "GET":
        case "DELETE":
                    var req = https.request(options,requestDone);
                    req.end();
                    break;
                    
        case "BADMETHOD":
        default:
                    var e = new Error('trakter: invalid method or not specified');
                    e.name = 'TrakterBadMethod';
                    e.code = 97;
                    next (e);
                    break;
    }

    function requestDone(res) {
        res.setEncoding('utf8');
        var responseString = '';
        res.on('error', function(err) {
            next (err,null);
        });
        res.on('data', function(data) {
            responseString += data;
        });
        res.on('end', function() {
            var err = checkError(options.method,res);
            if ( err !== null) {
                next (err);
            } else {
                next (null,JSON.parse(responseString));
            }
        });
    }
}
832408
function APIRequest(method, url) {
	var data, callback, opts, req, headers = messageHeaders(this);
	callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) );

	if (isNode) {
		opts = URL.parse(url);
		opts.method = method;
		opts.headers = headers;

		req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) {
			var chunks = [];
			res.on('data', function(c) { chunks[chunks.length] = c; });
			res.once('end', function() {
				chunks = Buffer.concat(chunks);
				Zlib.gunzip(chunks, function(err, uc) {
					if (!err) uc = uc.toString();
					try { res.body = JSON.parse(uc || chunks); } catch(e) {}
					return callback(null, res);
				});
			});
		});
		if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8");
		if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
		if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' );
		req.end();

		return req.once('error', function(e) { return callback(e.message); });
	}

	req = new XMLHttpRequest();
	req.open(method.toUpperCase(), url, true);
	for (var key in headers) {
		req.setRequestHeader(key, headers[key]);
	}
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			req.statusCode = req.status;
			req.statusMessage = req.statusText;
			try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); }
			callback(null, req);
		}
	};
	if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
	if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary);
	if (data) return req.send( data.result ? data.result : JSON.stringify(data) );
	req.send(null);
}
800260
func (h *BrandsHandler) MethodNotAllowedHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusMethodNotAllowed)
	return
}
393440
protected function methodNotAllowed(string $message = "Method not allowed."): Response
    {
        return $this->getResponse()
            ->setContent($message)
            ->setStatusCode(Response::HTTP_METHOD_NOT_ALLOWED);
    }
21980
def request(method, path)
        resource[path].send(method.to_sym, request_headers) { |response, request, result, &block|
          case response.code
            when 200
              response
            when 400
              if response.include? ' is required'
                raise ArgumentError.new(response)
              else
                raise BadRequestError.new(response)
              end
            else
              response.return!(request, result, &block)
          end
        }
      end
1258088
protected function method($method)
    {
        if (strtolower($this->request->getMethod()) != strtolower($method)) {
            throw new MethodNotAllowedException('No matching method for HTTP method "'.$this->request->getMethod().'"');
        }
        return true;
    }
609470
public function handleNotAllowed(ServerRequestInterface $request, ResponseInterface $response, array $methods)
    {
        if ($level = $this->shouldLog('not-allowed')) {
            $message = sprintf('%s on %s', $request->getMethod(), $request->getRequestTarget());
            $this->logEvent('not-allowed', $message, $level);
        }

        return $this->handler->handleNotAllowed($request, $response, $methods);
    }
367658
def allowed_methods(self, path_info=None):
        
        try:
            self.match(path_info, method="--")
        except MethodNotAllowed as e:
            return e.valid_methods
        except HTTPException:
            pass
        return []
149268
public Set<HttpMethod> allowedMethods(String uri) {
		QueryStringDecoder decoder = new QueryStringDecoder(uri);
		String[] tokens = PathPattern.removeSlashesAtBothEnds(decoder.path()).split("/");

		if (anyMethodRouter.anyMatched(tokens)) {
			return allAllowedMethods();
		}

		Set<HttpMethod> ret = new HashSet<HttpMethod>(routers.size());
		for (Map.Entry<HttpMethod, MethodlessRouter<T>> entry : routers.entrySet()) {
			MethodlessRouter<T> router = entry.getValue();
			if (router.anyMatched(tokens)) {
				HttpMethod method = entry.getKey();
				ret.add(method);
			}
		}

		return ret;
	}
846173
private StringBuffer determineMethodsAllowed(String path) {

        StringBuffer methodsAllowed = new StringBuffer();
        boolean exists = true;
        I_CmsRepositoryItem item = null;
        try {
            item = m_session.getItem(path);
        } catch (CmsException e) {
            exists = false;
        }

        if (!exists) {

            methodsAllowed.append(METHOD_OPTIONS);
            methodsAllowed.append(", ").append(METHOD_PUT);
            methodsAllowed.append(", ").append(METHOD_MKCOL);
            methodsAllowed.append(", ").append(METHOD_LOCK);
            return methodsAllowed;
        }

        // add standard http methods
        methodsAllowed.append(METHOD_OPTIONS);
        methodsAllowed.append(", ").append(METHOD_GET);
        methodsAllowed.append(", ").append(METHOD_HEAD);
        methodsAllowed.append(", ").append(METHOD_POST);
        methodsAllowed.append(", ").append(METHOD_DELETE);
        methodsAllowed.append(", ").append(METHOD_TRACE);

        // add special WebDAV methods
        methodsAllowed.append(", ").append(METHOD_LOCK);
        methodsAllowed.append(", ").append(METHOD_UNLOCK);
        methodsAllowed.append(", ").append(METHOD_MOVE);
        methodsAllowed.append(", ").append(METHOD_COPY);
        methodsAllowed.append(", ").append(METHOD_PROPPATCH);

        if (m_listings) {
            methodsAllowed.append(", ").append(METHOD_PROPFIND);
        }

        if (item != null) {
            if (!item.isCollection()) {
                methodsAllowed.append(", ").append(METHOD_PUT);
            }
        }
        return methodsAllowed;
    }
1126243
public function methodNotAllowed(string $requestMethod, array $allowedMethods): Error
    {
        $this->status->methodNotAllowed($allowedMethods);
        return Error::methodNotAllowed($requestMethod, $allowedMethods);
    }
42445
def forbidden(cls, errors=None):
        
        if cls.expose_status:  # pragma: no cover
            cls.response.content_type = 'application/json'
            cls.response._status_line = '403 Forbidden'

        return cls(403, errors=errors).to_json
339238
function validMethod(req, res, next) {
    if (httpMethods.indexOf(req.method) === -1) {
        res.sendStatus(405);
    } else {
        next();
    }
}
932812
def call(request)
      m = request.method.downcase.to_sym

      # Only respond to listed methods
      unless respond_to?(m)
        allowed = METHODS.select { |m| respond_to?(m) }.map(&:upcase).join(', ')
        return [
          405,
          { 'Content-Type' => 'text/plain', 'Allow' => allowed },
          "Method not allowed: '#{request.env['REQUEST_METHOD']}'"
        ]
      end

      begin
        send(m, request)
      rescue RestError => e
        error(e.response_code, e.error)
      end
    end
156974
func MethodNotAllowed(routes martini.Routes, w http.ResponseWriter, r *http.Request) {
	if methods := routes.MethodsFor(r.URL.Path); len(methods) != 0 {
		w.Header().Set("Allow", strings.Join(methods, ","))
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}