REST API无法通过C#Windows窗体访问

问题描述:

我使用Spring Boot和IntelliJ IDEA开发了一个REST API。该API已启动并正在运行。它可以通过Postman &访问,它提供了相关的JSON响应。REST API无法通过C#Windows窗体访问

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

@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); 
} 

如果我给出的网址为本地主机:8080 /学生/你好 JSON响应来到视觉工作室。但它不能作为Web参考添加。

enter image description here

,这是什么解决...?

+0

哟主要问题你的C#代码是它的Java代码 –

+2

我从来没有在.NET中使用REST API,但我始终认为Visual Studio中的“Web引用”旨在用于SOAP Web服务。要使用REST API,我认为您需要使用'HttpClient'或使用第三方库自行构建它。 – fharreau

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://*.com/a/10928807/2309376

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

+0

谢谢@Simply Ged。 &fharreau但我使用.NET只是为了从Web客户端应用程序中使用我的Web服务。我试图在NetBeans中将该Web服务添加到Java Web客户端。那里同样的问题。 Netbeans说:“无法确定服务的类型是WSDL还是WADL” – Chamith

+0

@Chamith:您是使用WinForms还是Web客户端?不清楚你问什么。无论如何,WSDL是SOAP Web服务的接口协议。我从来没有听说过WADL(只是看它和恕我直言,这是一个畸变,但这不是重点),我不是一个Java专家,但我不假设你的Java代码生成这样的文件。我想这就是为什么你无法在NetBeans中打开它。 – fharreau