如何从Angular 2打Asp.net Core Api
问题描述:
我是ASP.net Core和Angular 2的新手。我创建了我的angular 2安装程序,它的工作正常。但是当我尝试击打我的WebApi时,我无法击中。如何从Angular 2打Asp.net Core Api
namespace Angular2Application8.Controllers
{
[Produces("application/json")]
[Route("api/Hello")]
public class HelloController : Controller
{
StudentContext db = new StudentContext();
[HttpGet]
public string Ghouse()
{
var x = from n in db.StudentMaster
select n;
return "Hello Ghouse";
}
}
}
我想在http://localhost:1473/api/Hello/Ghouse
答
使用[Route("api/[controller]/[action]")]
所有Controllers
所以当你的controller
的名字是HelloController
和method
GHouse
您的网址应该是api/hello/ghouse
另外,还要确保你已经正确可配置routing。
答
打我的控制器例子中的属性的路由不允许你打所需的URL。
您需要更新路线模板或更改您呼叫的URL。
[Route("api/Hello")]
public class HelloController : Controller {
StudentContext db = new StudentContext();
[HttpGet] // Matches GET api/Hello
[HttpGet("Ghouse")] // Matches GET api/Hello/Ghouse
public string Ghouse() {
var x = from n in db.StudentMaster
select n;
return "Hello Ghouse";
}
}
您的Angular应用程序是否由您的API的相同主机托管? –
是的,它托管在相同的 –
请编辑您的问题,以包括您在浏览器控制台中获得的任何错误消息。 –