C# HttpClient PostAsync turns 204 into 404

我与影子孤独终老i 提交于 2019-12-03 06:08:43

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);

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!