【问题标题】:REST API cannot be accessed by the C# Windows FormC# Windows 窗体无法访问 REST API
【发布时间】:2017-05-04 22:26:45
【问题描述】:

我已经使用 Spring Boot 和 IntelliJ IDEA 开发了一个 REST API。该 API 已启动并正在运行。 Postman 可以访问它并提供相关的 JSON 响应。

然后我尝试从 C# windows 窗体应用程序访问它。我试图将其添加为网络参考。但是该按钮已被禁用。 我的代码有什么问题?

@RestController
@RequestMapping("/students")
public class StudentController {

@Autowired
private StudentService studentService;

@RequestMapping(value="/hello")
String home() {
    return "Hello World!";
}

@RequestMapping(value="getAllStudents",method = RequestMethod.GET)
public Collection<Student> getAllStudents(){
    return studentService.getAllStudents();
}

@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public Student getStudentById(@PathVariable("id") int id)
{
    return studentService.getStudentById(id);
}


@RequestMapping(value = "/{id}" , method = RequestMethod.DELETE)
public void deleteStudentById(@PathVariable("id") int id)
{
studentService.removeStudentById(id);
}

如果我将 URL 指定为 localhost:8080/students/hello,则 JSON 响应会到达 Visual Studio。但它不能作为网络参考添加。

对此有什么解决方案...?

【问题讨论】:

  • 你的 C# 代码的主要问题是它的 Java 代码
  • 我从未在 .NET 中使用过 REST API,但我始终相信 Visual Studio 中的 Web reference 旨在与 SOAP Web 服务一起使用。要使用 REST API,我认为您需要使用 HttpClient 自行构建它或使用 3rd 方库。

标签: java c# rest intellij-idea spring-boot


【解决方案1】:

Visual Studio 中的 Web 引用适用于 SOAP/ASMX Web 服务。如果您正在调用 REST API,那么正如 @fharreau 评论的那样,您将需要使用 HttpClient。

该链接向您展示了如何操作,但可能难以阅读/遵循:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

这个 SO 答案可能会更好

https://stackoverflow.com/a/10928807/2309376

在 SO 答案中,您需要将“http://www.contoso.com/”替换为您的网址“http://localhost:8080/students/hello

【讨论】:

  • 谢谢@Simply Ged。 & fharreau 但我使用 .NET 只是为了从 Web 客户端应用程序使用我的 Web 服务。我试图将该 Web 服务添加到 netbeans 中的 Java Web 客户端。那里同样的问题。 Netbeans 说“无法确定服务是 WSDL 还是 WADL 类型”
  • @Chamith:您使用的是 WinForms 还是 Web 客户端?不清楚你问什么。无论如何,WSDL 是 SOAP Web 服务的接口契约。我从未听说过 WADL(只是看看它和恕我直言,这是一种偏差,但这不是重点)而且我不是 Java 专家,但我认为您的 Java 代码中没有任何内容生成这样的文件。我想这就是为什么你不能在 NetBeans 中打开它的原因。
猜你喜欢
  • 2019-04-04
  • 1970-01-01
  • 2023-03-09
  • 2014-01-28
  • 1970-01-01
  • 2014-09-03
  • 2018-05-21
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多