首页 > 解决方案 > 带有 C# 客户端的 ASP.NET Web API Core 5.0 中的错误

问题描述

我正在尝试在 ASP.NET Core 5.0 中创建一个 HTTP POST Web API,在该 API 中,我可以在 Dictionary 变量中的键/值对中以字符串形式接收任何数据,例如 String、Int 作为 String 或 Binary、Image 作为 Base64 PostValues

网络接口:

public class WebserviceController : ControllerBase
{
    [HttpPost]
    [Consumes("application/json")]
    [Produces("application/json")]
    public String Post([FromBody] Dictionary<String, String> PostValues)
    {
        return JsonConvert.SerializeObject(new ClassResponse(true, PostValues));
    }
}

客户:

RestClient client = new RestClient("https://localhost:44395/webservice");
RestRequest request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", "application/json");

request.AddParameter("Key1", "Value1");
request.AddParameter("Key2", "Value2");

IRestResponse response = client.Post<String>(request);

Response = JsonConvert.DeserializeObject<ClassResponse>(response.Content);

传递/返回数据的通用类:

public class ClassResponse
{
    public ClassResponse(Boolean Success, Object Result)
    {
        this.Success = true;
        this.Result = Result;
    }

    public Boolean Success;

    public Object Result;
}

response.Content但是我在:{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-7462e05ef46bf946bc7d102a93cc479e-06107777372f8f46-00","errors":{"$":["'w' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}response.StatusCodeas中得到错误(不是例外) :System.Net.HttpStatusCode.BadRequest

标签: asp.netasp.net-web-apihttp-post

解决方案


推荐阅读