当前位置: 首页 > article >正文

Dify创建自定义工具,调用ASP.NET Core WebAPI时的注意事项(出现错误:Reached maximum retries (3) for URL ...)

1、要配置Swagger

using Microsoft.AspNetCore.Mvc;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
        builder => builder.WithOrigins("http://172.20.10.7:5619") // 替换为你的Dify域名
                            .AllowAnyMethod()
                            .AllowAnyHeader());
});

// 添加控制器服务
builder.Services.AddControllers();

// 配置Swagger
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "PowerApi",
        Version = "v1",
        Description = "A simple API to calculate powers of a number from 0 to 50.",
        Contact = new OpenApiContact
        {
            Name = "Your Name",
            Email = "your.email@example.com",
            Url = new System.Uri("https://example.com")
        }
    });

    // 定义Schema
    c.MapType<Dictionary<int, double>>(() => new OpenApiSchema
    {
        Type = "object",
        AdditionalProperties = new OpenApiSchema
        {
            Type = "number"
        }
    });
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "PowerApi v1");
        c.DocumentTitle = "PowerApi Documentation";
    });
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseCookiePolicy();

app.Use(async (context, next) =>
{
    context.Response.Headers.Add("Content-Security-Policy", "script-src 'self';");
    await next();
});

app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.Run();

注意:IP地址的部分一定要写对了!不能是localhost或者127.0.0.1

2、launchSettings.json中

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1393",
      "sslPort": 44372
    }
  },
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://172.20.10.7:5169",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "https://172.20.10.7:7007;http://172.20.10.7:5169",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

注意:IP地址的部分一定要写对了!不能是localhost或者127.0.0.1

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace PowerApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PowerController : ControllerBase
    {
        [HttpGet("{number}")]
        public IActionResult GetPowers(double number)
        {
            try
            {
                var powers = new Dictionary<int, double>();

                for (int i = 0; i <= 50; i++)
                {
                    powers[i] = Math.Pow(number, i);
                }

                // 返回JSON格式的幂运算结果
                return Ok(new { powers = powers });
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Internal server error: {ex.Message}");
            }
        }
    }
}

3、符合OpenAPI Swagger规范的Schema:

{
      "openapi": "3.1.0",
      "info": {
        "title": "Get weather data",
        "description": "Retrieves current weather data for a location.",
        "version": "v1.0.0"
      },
      "servers": [
        {
          "url": "http://172.20.10.7:5169"
        }
      ],
      "paths": {
        "/api/folder": {
          "get": {
            "description": "Get temperature for a specific location",
            "operationId": "GetCurrentWeather",
            "deprecated": false
          }
        }
      },
      "components": {
        "schemas": {}
      }
 }

注意:IP地址的部分一定要写对了!不能是localhost或者127.0.0.1!

4、端口规则,一定要加。

结果:

好了,现在有手有脚了。


http://www.kler.cn/a/316915.html

相关文章:

  • 平替 Spring 正当时!Solon v3.0.3 发布
  • NVIDIA NIM 简介
  • 记录日志中logback和log4j2不能共存的问题
  • 由播客转向个人定制的音频频道(1)平台搭建
  • 【时间之外】IT人求职和创业应知【34】-人和机器人,机器人更可靠
  • C 语言标准库 - <errno.h>
  • Java_Day03学习
  • 前端vue左侧树的一整套功能实现(一):vue2+vite封装v-resize指令,实现左侧树拖拽宽度和折叠展开
  • Java面向对象——内部类(成员内部类、静态内部类、局部内部类、匿名内部类,完整详解附有代码+案例)
  • 江协科技STM32学习- P14 示例程序(定时器定时中断和定时器外部时钟)
  • web基础—dvwa靶场(十一)CSP Bypass
  • Linux相关概念和重要知识点(6)(make、makefile、gdb)
  • SQLServer数据分页
  • Python 中的函数装饰器:理解 @property、Getter 和 Setter 方法
  • (算法)大数的进制转换
  • ESP32-WROOM-32 [创建AP站点-客户端-TCP透传]
  • PostgreSQL中的regexp_split_to_table函数详解,拆分字段为多行
  • C++之STL—vector容器进阶篇
  • C++ STL全面解析:六大核心组件之一----序列式容器(vector和List)(STL进阶学习)
  • H5网页嵌在APP内部 手机锁屏后再打开 setInterval会重复执行
  • 【Git原理与使用】版本管理与分支管理(1)
  • LIN总线CAPL函数—— 设置报头同步间隔场长度(linSetBreakLength)
  • Redis数据结构之list列表
  • 116页可编辑PPT全面了解数据治理体系、平台,数据质量数据标准
  • Algo-Lab 2 Stack Queue ADT
  • 重修设计模式-设计原则