简体   繁体   English

如何从Web API项目调用通知项目中的post方法

[英]How to call the post method in notification project from web api project

Here is my code , there are 2 projects web api project and notification project, How to access post method of notification project from web api project. 这是我的代码,有2个项目Web api项目和通知项目,如何从Web api项目访问通知项目的发布方法。

namespace NotificationApi.Controllers
{

    [Route("api/[controller]/[action]")]
    public class MessageController : Controller
    {
        private IHubContext<NotifyHub, ITypedHubClient> _hubContext;

        public MessageController (IHubContext<NotifyHub, ITypedHubClient> hubContext)
        {
            _hubContext = hubContext;
            MessageVM messageVM = new MessageVM();
            messageVM.Payload = "hii";
            messageVM.Type = "success";
              this.Post(messageVM);
    }


        [HttpPost]
        [DisableCors]
        public string Post([FromBody]MessageVM msg)
        {
            string retMessage = string.Empty;
            try
            {

        _hubContext.Clients.All.BroadcastMessage(msg.Type, msg.Payload);
                retMessage = "Success";
            }
            catch (Exception e)
            {
                retMessage = e.ToString();
            }
            return retMessage;
        }
    }
}

For accessing method between two web api projecct, you could try HttpClient to send request. 对于两个Web API项目之间的访问方法,您可以尝试HttpClient发送请求。

  • MessageVM

      public class MessageVM { public int Id { get; set; } public string Name { get; set; } } 
  • Method from web api Web API中的方法

     [Route("api/[controller]/[action]")] [ApiController] public class HttpClientController : ControllerBase { private readonly HttpClient _httpClient; public HttpClientController(HttpClient httpClient) { _httpClient = httpClient; } public async Task CallWebApi() { string url = @"https://localhost:44342/api/message/post"; var model = new MessageVM { Id = 1, Name = "Test" }; var response = await _httpClient.PostAsJsonAsync(url, model); var result = await response.Content.ReadAsStringAsync(); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM