C# HttpClient PostAsync turns 204 into 404

后端 未结 2 1518
生来不讨喜
生来不讨喜 2021-02-08 04:00

Given this WebApi service:

[ActionName(\"KillPerson\")]
[HttpPost]
public void KillPerson([FromBody] long id)
{
    // Kill
}

And this HttpClie

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-08 04:25

    Adding the HttpResponseMessage returntype to the method is the documented way of doing this, so the solution you have found is the best really.

    But if you don't want to change all your void methods that way, an alternative could be to add a delegating handler to change the response code on the fly - something like this:

    public class ResponseHandler : DelegatingHandler
    {
        protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = base.SendAsync(request, cancellationToken);
    
            if (request.Method == HttpMethod.Post)
            {
                response.Result.StatusCode = response.Result.IsSuccessStatusCode ? System.Net.HttpStatusCode.OK : response.Result.StatusCode;
            }
            return response;
       }
    }
    

    Note: This will change the statuscode for all your post methods (when successful). You would have to add some code if you only want it done for specific routes/methods (if you need different post methods to be treated differently).

提交回复
热议问题