提问者:小点点

API 终结点 C# Web API 不支持的媒体类型


我有一个 API 网关,它将应用程序设置文件作为字符串发送,我更新 UI 中的一些密钥,然后我想将其提交回网关以替换服务器上的设置。当我将 JSON 字符串提交回 API 时,我收到错误 415 不支持的媒体类型。

这是endpoint

        [HttpPost("{app}/set")] // POST /api/settings/{app}/set
        public bool Set(string app, [FromBody] string content)
        {
            _logger.LogInformation($"recieved request on settings/{app}/set, id: {_requestId}");
            var response = false;
            try
            {
                System.IO.File.WriteAllText(GetAppSettingsPath(app), content, Encoding.UTF8);
                _logger.LogInformation($"Completed request for requestId: {_requestId}");
                response = true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error on requestId, {_requestId}");
            }
            return response;
        }

这是我的客户服务

public ApiService(ILogger<ApiService> logger, IOptions<AppSettings> appsettings, HttpClient client)
{
    _logger = logger;
    _baseUri = new Uri(appsettings.Value.GatewayBaseURL);
    client.DefaultRequestHeaders.Accept.Clear();
    client.Timeout = Timeout.InfiniteTimeSpan;
    _client = client;
}
            
public async Task<bool> SetAppSettings(string app, string content)
{
    var response = false; //always fails by default
    try
    {
        var httpRequest = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(_baseUri, string.Concat("api/settings/", app, "/set")), Content = new StringContent(content, Encoding.UTF8) };
        httpRequest.Headers.Add("content-type", "text/plain");
        var httpResponse = await _client.SendAsync(httpRequest).ConfigureAwait(false);
        httpResponse.EnsureSuccessStatusCode();
        var responseBody = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
        response = bool.TryParse(responseBody, out var parseValue) ? parseValue : false; 
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, $"Failed to set the settings for application, {app}");
    }
    return response;
}

我已经阅读了一些堆栈答案试图解决此问题,但我不确定我是否需要更改endpoint、客户端、requestMessage 或所有这些。我也希望得到一些关于使用哪个标头以及如何正确声明它的指导。其中大多数都说应用“application/json”,但我不确定这是否适合我的情况。1 2 3 4

更新 我已经将我的客户端更改为使用 WebClient 而不是使用闪烁的代码。现在我收到 400 错误请求,而不是 415 不支持的媒体类型错误。

    WebClient client = new WebClient();
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var url = new Uri(_baseUri, string.Concat("api/settings/", app, "/set"));
    var responseString = client.UploadString(url, "POST", content);
    response = bool.TryParse(responseString, out var result) && result;

共1个答案

匿名用户

我想通了。我想用于“文本/纯文本”的媒体类型需要不同的处理,并且endpoint签名中的参数导致了问题。这篇文章有所帮助。

更新的终结点:

[HttpPost("{app}/set")] // POST /api/settings/{app}/set
public bool Set(string app)
{
    string jsonString = null;
    using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
    {
        jsonString = reader.ReadToEndAsync().Result;
    }
    System.IO.File.WriteAllText(GetAppSettingsPath(app), jsonString, Encoding.UTF8);
}

更新的客户端:

    WebClient client = new WebClient();
    client.Headers[HttpRequestHeader.ContentType] = "text/plain";
    var url = new Uri(_baseUri, string.Concat("api/settings/", app, "/set"));
    var responseString = client.UploadString(url, "POST", content);
    response = bool.TryParse(responseString, out var result) && result;