映射参数时如何在WCF REST中处理异常 [英] How to handle exceptions in WCF REST when mapping parameters

查看:78
本文介绍了映射参数时如何在WCF REST中处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

 

我正在将某些WCF REST服务用作企业应用程序的API.

I am working on some WCF REST service as an API for an enterprise application.

接口中我的方法的原型类似于此:

A prototype of my method in the interface looks similar to this:

 

 

[OperationContract]

[WebGet(UriTemplate = "sites?limit={limit}")]

List<Sites> GetSites(int limit);

从浏览器查询字符串传递整数时,一切正常.

When an integer being passed from the browser query string - everything works fine.

但是,当传递字符串时,映射失败,并出现以下错误:

However when a string is being passed mapping fails with the following error:


The server encountered an error processing the request. The exception message is 'Input string was not in a correct format.'. See server logs for more details. The exception stack trace is: 

at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Xml.XmlConvert.ToInt32(String s) at System.ServiceModel.Dispatcher.QueryStringConverter.ConvertStringToValue(String parameter, Type parameterType) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

推荐答案

如果您想自己处理解析,可以将参数作为字符串,进行解析,然后在解析失败的情况下返回适当的错误,如下例所示.

If you want to handle the parsing yourself, you can take the parameter as a string, parse it then return an appropriate error if the parsing did not succeed, like in the example below.


  public class Post_b5efb12c_3920_41f7_a478_349fd4607875
  {
    [ServiceContract]
    public interface ITest
    {
      [OperationContract]
      [WebGet(UriTemplate = "sites?limit={limitStr}")]
      string DoSomething(string limitStr);
    }
    public class Service : ITest
    {
      public string DoSomething(string limitStr)
      {
        int limit;
        if (!int.TryParse(limitStr, out limit))
        {
          throw new WebFaultException<string>("limit parameter must be an integer", HttpStatusCode.BadRequest);
        }

        return "Limit is " + limit;
      }
    }
    public static void SendGet(string uri)
    {
      HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
      req.Method = "GET";

      HttpWebResponse resp;
      try
      {
        resp = (HttpWebResponse)req.GetResponse();
      }
      catch (WebException e)
      {
        resp = (HttpWebResponse)e.Response;
      }

      Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
      foreach (string headerName in resp.Headers.AllKeys)
      {
        Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
      }
      Console.WriteLine();
      Stream respStream = resp.GetResponseStream();
      Console.WriteLine(new StreamReader(respStream).ReadToEnd());

      Console.WriteLine();
      Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
      Console.WriteLine();
    }
    public static void Test()
    {
      string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
      WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
      host.Open();
      Console.WriteLine("Host opened");

      SendGet(baseAddress + "/sites?limit=123");
      SendGet(baseAddress + "/sites?limit=abc");

      Console.Write("Press ENTER to close the host");
      Console.ReadLine();
      host.Close();
    }
  }


这篇关于映射参数时如何在WCF REST中处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆