如何将参数从 MVC5 项目传递给 Rest WCF 服务

How pass parameter to Rest WCF Service from MVC5 project

我有一个 WCF Rest 服务(使用 Json)获取用户名和密码以及 returns 客户信息。这是方法接口。

   //Get Customer by Name
    [OperationContract]
    [WebInvoke
       (UriTemplate = "/GetCustomerByName",
        Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json
        )]
    List<Model.Customer> GetCustomerByName(Model.CustomerName CustomerData);

我需要在 MVC5 中调用此方法并将参数传递给它。不确定如何传递参数。

我是这样调用服务的:

readonly string customerServiceUri = "http://localhost:63674/CSA.svc/";
 public ActionResult SearchByName(InputData model)
    {
        List<CustomerModel> customerModel = new List<CustomerModel>();

        if (ModelState.IsValid)
        {
            if (model != null)
            {
                using (WebClient webclient = new WebClient())
                {
                    string jsonStr = webclient.DownloadString(string.Format("{0}GetCustomerByName?CustomerData={1}", customerServiceUri, model));

                    if (!string.IsNullOrWhiteSpace(jsonStr))
                    {
                        var result = JsonConvert.DeserializeObject<Models.CustomerModel.Result>(jsonStr);

                        if (result != null)
                        {
                            customerModel = result.GetCustomersByNameResult;
                        }
                    }
                }
            }
        }
        return View(customerModel);
    }

我在这一行遇到错误:

 string jsonStr = webclient.DownloadString(string.Format("{0}GetCustomerByName?CustomerData={1}", customerServiceUri, model));

这是错误:

The remote server returned an error: (405) Method Not Allowed.

这是 InputData class:

 public class InputData
  {

      public string First_Name { get; set; }
      public string Last_Name { get; set; }
  }

问题是那行代码是调用服务的,错了。因为您传递了 url 中的值,所以这行代码发出了 GET 请求, 而不是 POST。如果您愿意提出 POST 请求,请 follow this answer.

代码有什么问题?

string jsonStr = webclient.DownloadString(string.Format("{0}GetCustomerByName?CustomerData={1}", customerServiceUri, model));

1) 抛出此错误 (405) Method Not Allowed because you expecting 因为需要 POST 请求并且发出了 GET 请求。

2) 这将输出如下内容:http://localhost:63674/CSA.svc/GetCustomerByName?CustomerData=[SolutionName].[ProjectName].InputData

发生这种情况是因为 C# 不知道如何以您想要的方式将 InputData 转换为字符串,为此您必须 覆盖 方法 ToString()

可能的解决方案

尝试发出 GET 请求,您必须以这种方式调用服务(稍作修改)

string jsonStr = webclient.DownloadString(string.Format("{0}GetCustomerByName?firstName={1}&lastName={2}", customerServiceUri, model.First_Name, model.Last_Name));

您必须修改服务以匹配我为 GET 请求所做的示例。

//Get Customer by Name
[OperationContract]
[WebGet(UriTemplate = "GetCustomerByName?firstName={firstName}&lastName={lastName}")]
List<Model.Customer> GetCustomerByName(string firstName, string lastName);