[英]How can I call a method of type async Task<IHttpActionResult> from another project?
I have a C# Azure application where I have two websites in my solution. 我有一个C# Azure应用程序,在我的解决方案中有两个网站。 One is an outward facing website that a user hits, and the other is an API that the website hits to create users, etc.
一个是用户点击的面向外部的网站,另一个是该网站点击以创建用户的API。
Inside the second project (the API project), I've build a Register
method with the code: 在第二个项目(API项目)中,我使用以下代码构建了一个
Register
方法:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(UserModel userModel)
{
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
IdentityResult result = await _repo.RegisterUser(userModel);
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null) {
return errorResult;
}
return Ok();
}
This works great when calling this through a URL, and it works great when I call it via javascript in the website project. 通过URL调用时效果很好,而通过网站项目中的javascript调用时效果很好。
However, I would like to now call this method from the server side of the website project, yet when I use the code: 但是,我现在想从网站项目的服务器端调用此方法,但是当我使用代码时:
SecondProject.API.Controllers.AccountController UserApiController = new SecondProject.API.Controllers.AccountController();
UserApiController.Register(UserApiModel);
visual studio warns me I should use await
. 视觉工作室警告我我应该使用
await
。
So if I add: 因此,如果我添加:
await UserApiController.Register(UserApiModel);
visual studio tells me the await
operator can only be used in an async method. visual studio告诉我,
await
操作符只能在异步方法中使用。
How can I call my Register
method inside SecondProject.API
from my first project on via server code???? 如何通过服务器代码从我的第一个项目在
SecondProject.API
调用我的Register
方法?
You need to declare the calling method as async
. 您需要将调用方法声明为
async
。
public async Task CallingMethod()
{
//...
SecondProject.API.Controllers.AccountController UserApiController = new SecondProject.API.Controllers.AccountController();
await UserApiController.Register(UserApiModel);
//...
}
EDIT: 编辑:
In saying that, you should not be creating controller and calling methods in code. 话虽如此,您不应该在代码中创建控制器和调用方法。 You should be using the repository, as you do in your controller method.
您应该像在控制器方法中一样使用存储库。
public async Task CallingMethod()
{
//...
IdentityResult result = await _repo.RegisterUser(userModel);
//Do something with the result
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.