【问题标题】:C# post to asp.net webapi Apiexception "The HTTP status code of the response was not excepted (201)."C# 发布到 asp.net webapi Apiexception“响应的 HTTP 状态代码未排除 (201)。”
【发布时间】:2021-12-09 18:49:36
【问题描述】:

我希望你能在这里帮助我。

我正在创建一个读取日志文件并将特定条目发送到 Webapi 的 C# 应用程序。 到目前为止,它并不漂亮,需要进行一些大修,但它或多或少地工作了。

程序使用多个等待指令,因为日志文件生成条目的速度非常快,以至于 http Post 不够快;)

在我的第一个方法中,我读取了日志文件并将一些符合我的条件的行发送到另一个方法以使用此语句将其删除

Task<string> marketstring = MarketstringAsync(s);
                                await marketstring;

在 Marketstring 方法中,我用我需要的信息在不同部分剪断了行,然后将其发送到我的 api 方法:

Task<string> MarketSendApi = MarketSendApiAsync(order);
                string apiresult = await MarketSendApi;

现在我们在 apisend 方法中。 我在 asp.net 核心团队的教程视频之后创建了它,并测试了一些东西以使其运行。

private static async Task<string> MarketSendApiAsync(string sendtoapi)
        {
            Console.WriteLine("api");
            //Console.WriteLine(sendtoapi);

            var httpClient = new HttpClient();
            var client = new swaggerClient("https://localhost:7250/", httpClient);
            //var results = await client.MarketDatumAsync(sendtoapi);
            //string res = results.Id;
            
            //return results.Playername;

            System.Collections.Generic.ICollection<MarketDatum> marketData = (System.Collections.Generic.ICollection<MarketDatum>)await client.MarketDatumAsync(sendtoapi);
            //string apiresult = marketData;


            //if (marketData == null)
            //{
            //    return "error";
            //};

            //return marketData;
            //return new StatusCodeResult(await client.MarketDatumAsync(sendtoapi)
            //return await client.MarketDatumAsync(sendtoapi);
            return "test";

        }

帖子工作正常,数据在我的 webapi 上创建,但现在程序“崩溃”,在 await 市场字符串出现以下异常;第一种方法与

market_api.ApiException: "响应的 HTTP 状态码不是 预期 (201)。

状态:201 响应:“myData”

我的 api 方法如下所示:

public ActionResult<MarketDatum> Set([FromBody] string value)
        {
            if (value == "")
            {
                return BadRequest();
            }
            using (var context = new CoreDbContext())
            {
                //add new Orders
                MarketDatum orders = new MarketDatum();
    .....
    return CreatedAtAction(nameof(GetbyID), new { id = orders.Id }, orders);

我希望我以一种可以理解的方式解释了我的问题,并且你找到了我的问题 谢谢;)

【问题讨论】:

    标签: c# asp.net post webapi


    【解决方案1】:

    太澄清了一些,在哪一行抛出异常?

    我认为引发错误是因为您使用的是 CreatedAtAction。 看这里:https://docs.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-6.0

    【讨论】:

    • 啊抱歉,我忘记了这一点。错误出现在等待市场字符串;第一种方法
    猜你喜欢
    • 2012-02-14
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    相关资源
    最近更新 更多