API 端点 C# web API 不支持的媒体类型

Unsupported Media Type for API Endpoint C# web API

我有一个 API 网关,它以字符串形式发送一个 appsettings 文件,我更新了 UI 中的一些键,然后我想将它提交回网关以替换设置服务器。当我将 JSON 字符串提交回 API.

时出现错误 415 Unsupported media type

这里是终点

        [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;
}

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

更新 我已经改变我的客户端使用 WebClient 而不是 flowing 代码。现在我收到 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;

我明白了。我想用于“text/plain”的媒体类型需要不同的处理方式,端点签名中的参数导致了问题。 This article helped.

更新端点:

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