在 MVC 5 中调用 WCF Restful POST 方法

Posted

技术标签:

【中文标题】在 MVC 5 中调用 WCF Restful POST 方法【英文标题】:Call WCF Restful POST Method in MVC 5 【发布时间】:2016-11-22 13:02:16 【问题描述】:

我必须使用 GET 和 POST 创建简单的 WCF Web 服务。请看下面的源代码

public interface ISample

    [OperationContract]
    [WebGet(UriTemplate = "/GetDEPT", RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
    Task<IEnumerable<DEPT>> GetDEPT();

    [OperationContract]
    [WebInvoke(UriTemplate = "UpdateDEPT?Id=Id&StatusId=StatusId", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    Task<bool> UpdateDEPT(List<DEPT> DEPT, string Id, string StatusId);

ISample 接口实现:示例

public class Sample: ISample

    public async Task<IEnumerable<DEPTt>> GetDEPT()
    
        return await DEPTBO.GetDEPT();
    

public async Task<bool> UpdateDEPT(List<DEPTt> DEPT, string Id, string StatusId)
    
        return await DEPTBO.UpdateDEPTAsync(Id, DEPT, StatusId);
    
 

如何在 MVC 5 中调用这个 WCF Restful 服务?

请帮助我 MVC 应用程序中的服务集成

【问题讨论】:

【参考方案1】:

现在我找到了我的问题的解决方案。 我已经为代理创建类

namespace WCF.WCFService

public static class WebService<T> where T : class

    public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];
    public static IEnumerable<T> GetDataFromService(string Method, string param = "")
    
        var client = new WebClient();

        var data = client.DownloadData(appSettings + Method + param);
        var stream = new System.IO.MemoryStream(data);
        var obj = new DataContractJsonSerializer(typeof(IEnumerable<T>));
        var result = obj.ReadObject(stream);
        IEnumerable<T> Ts = (IEnumerable<T>)result;
        return Ts;
    


public static class WebServiceUpdate

    public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];
    public static bool GetDataFromService_Update(string Method, List<CNHDataModel.CustomEntities.Port> portData, string param = "")
    
        bool _res = false;
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<CNHDataModel.CustomEntities.Port>));
        MemoryStream mem = new MemoryStream();
        serializer.WriteObject(mem, portData);
        string data =
            Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
        WebClient webClient = new WebClient();
        webClient.Headers["Content-type"] = "application/json";
        webClient.Encoding = Encoding.UTF8;
        webClient.UploadString(appSettings + Method + param, "POST", data);
        _res = true;
        bool Ts = (bool)_res;
        return Ts;
    


下面,从控制器调用服务代理

public class DEPTController : Controller

    [ActionName("DEPTView")]
    public ActionResult DEPTViewAsync()
    
try

            IEnumerable<DEPT> DEPT = CNHService.WebService<DEPT>.GetDataFromService("GetDEPT");

            if (port == null)
            
                return HttpNotFound();
            
            IEnumerable<Status> Status = CNHService.WebService<Status>.GetDataFromService("GetStatusAsync");
            if (port == null || Status == null)
            
                return HttpNotFound();
            
        
        catch (Exception ex)
        

        
        return View();
    



[HttpPost]
    [ActionName("DEPTView")]
    public ActionResult DEPTViewAsync([Bind(Include = "id,Statusid")] DEPT DEPTMENT)
    
        try
        
            List<DEPT> objDEPT = Session["DEPTItems"] as List<DEPT>;
            List<DEPTStatus> objStatus = Session["DEPTIStatus"] as List<PortStatus>;
            ViewBag.DEPTList = new SelectList(objDEPTt, "id", "Name");
            ViewBag.DEPTStatusList = new SelectList(objStatus, "id", "Name");
            if (ModelState.IsValid)
            
                WebServiceUpdate.GetDataFromService_Update("UpdateDEPT", objDEPT, "?Id=" + DEPTMENT.Id + "&StatusId=" + DEPTMENT.Statusid);
                setting.Message = true;
            
            else
            
                return View(setting);
            

        
        catch (Exception ex)
        

        
        return View(setting);



我希望这段代码对 MVC 5 中的 WCF Restful 服务集成有所帮助

【讨论】:

以上是关于在 MVC 5 中调用 WCF Restful POST 方法的主要内容,如果未能解决你的问题,请参考以下文章

在 .NET 中开发新的 RESTful Web 服务——我应该从哪里开始? ASP.NET-MVC,WCF?

RESTful 服务:WCF 与 ASP.NET MVC

表单身份验证、ASP.NET MVC 和 WCF RESTful 服务

Restful风格wcf调用4——权限认证

Restful风格wcf调用3——Stream

如何理解一个服务调用是“Restful 服务调用”还是“标准 wcf 调用”?