简体   繁体   中英

POST Request returning 404 in C# but not in Postman

I have a simple helper to send post requests and returns the result, it's supposed to communicate with a custom built API, everything is working apart from a specific url.

My helper method is as follows (Using RestSharp)

    public static IRestResponse POSTResponse( string URL, List<Parameter> Parameters )
    {
        var restClient = new RestClient( URL );

        var restRequest = new RestRequest( Method.POST )
        {
            RequestFormat = DataFormat.Json
        };

        Parameters.ForEach( p =>
        {
            restRequest.AddParameter( p );
        } );

        var result = restClient.Post(restRequest);
        return result;
    }

My request is as follow:

    var Values = new List<Parameter>();
    Values.AddRange( ApiCredentialsParams );
    Values.Add( new Parameter("Key", form.Key, ParameterType.RequestBody) );
    Values.Add( new Parameter("Value", form.Value, ParameterType.RequestBody) );

    var response = Network.POSTResponse( Url, Values );

I have tested the same url on postman, passing the same parameters in the "Params" tab,

Result was Postman returned what I expected, while c# returned 404.

Any help is greatly appreciated.

I have found the fix for this issue,

Postman was sending the data as if it was a get request, the bug was in 2 places,

API Side, I have updated the method to include the [FromBody] tag for parameters

public HttpResponseMessage Update( [FromBody] MyModel model )

As for the requesting side,

public static IRestResponse POSTResponse( string URL, List<Parameter> Parameters )
    {
        var client = new RestClient( URL );
        var request = new RestRequest( Method.POST )
        {
            RequestFormat = DataFormat.Json,
            Method = Method.POST
        };

        foreach (var parameter in parameters)
        {
            switch( parameter.Type)
            {
                case ParameterType.HttpHeader:
                    request.AddHeader( parameter.Name, (string)parameter.Value );
                    break;
                case ParameterType.QueryString:
                    request.AddQueryParameter( parameter.Name, (string)parameter.Value );
                    break;
                case ParameterType.GetOrPost:
                    request.AddParameter( parameter.Name, (string)parameter.Value );
                    break;
            }
        }

        var result = client.Post( request );
        return result;
    }

TODO add more parameter type support, but all is going well now, thanks for everyone who tried to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM