C# HttpClient PostAsync turns 204 into 404

后端 未结 2 1517
生来不讨喜
生来不讨喜 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:24

    Finally figured this out. Seems you get a choice of using either browser or client HTTP handling in Silverlight. When using browser HTTP handling a lot of stuff is unsupported - including various response codes and headers. Adding these lines before calling HttpClient fixed it:

    WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
    WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
    
    0 讨论(0)
  • 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<HttpResponseMessage> 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).

    0 讨论(0)
提交回复
热议问题