2017-03-23 28 views
-1

服务器端代码,返回文件如何在Web客户端请求中检索custome错误消息?

[HttpGet] 
public HttpResponseMessage GetVersionList(string Credentials, string VersionNumber) 
{ 
    try 
    { 
     string UserLoginStatus = objUtility.LoginUser(objUtility.GetUserName(Credentials), objUtility.GetPassWord(Credentials)); 

     if (UserLoginStatus == "OK") 
     { 
      var path = objUtility.GetFileName(VersionNumber); 

      if (path != null) 
      { 
       return FileAsAttachment(path, VersionNumber + ".exe"); 
      } 
      else 
      {    
       return Request.CreateErrorResponse(HttpStatusCode.OK, "File Not Found."); 
      } 
     } 
     else 
     { 
      // Return reason why it failed. 
      // It could be not authorized user, Not Active user, UID/Password wrong etc. 
      // Store into UserLoginStatus variable and pass show to client 
      return Request.CreateResponse<string>(HttpStatusCode.OK, UserLoginStatus); 
     } 
    } 
    catch (System.Exception ex) 
    { 
     return Request.CreateResponse<string>(HttpStatusCode.OK, ex.Message); 
    } 

} 

// Win app code to download file 
using (WebClient webClient = new WebClient()) 
{ 
      try 
      { 
       webClient.DownloadFile(serverUrl, (txtPath.Text + "\\" + txtVersion.Text + ".exe")); 
      } 
      catch (WebException wex) 
      { 
       // Show error message here 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     lblStatus.Text = ex.InnerException + " <br> " + ex.Message; 
    } 
} 

回答

0

这是我如何做它最近休息了一会服务,我写了一个POS机。 (myErrorType就是无论什么类,你实际上是使用虚拟...)

using (var response = request.GetResponse()) 
       { 
using (var reader = new StreamReader(response.GetResponseStream())) 
          { 
           var reply = reader.ReadToEnd(); 
           myErrorType result = Newtonsoft.Json.JsonConvert.DeserializeObject<myErrorType>(reply); 
           return result.Status; 
           // do something with the results 
          } 
} 

抛出一个自定义错误:

myErrorType errresponse = new myErrorType();//dummy class, create your own... 
throw new WebFaultException<myErrorType>(errresponse, HttpStatusCode.BadRequest); 
+0

感谢评论三分球。但是,我将从Windows应用程序调用服务器端函数。如果我可以提供一些代码片段,这将是很大的帮助。 – Mark

+0

你还需要什么?您是否需要服务器端代码来查看实际的错误?您的问题是“如何在Web客户端请求中检索custome错误消息?”...我相信我已经回答了...但我会更新我的答案。 – Trey

+0

实际上,如果Web API正在像 返回Request.CreateErrorResponse(HttpStatusCode.NotFound,“File Not Found on Server。”); 如何在窗口应用程序中检索Catch块中的文本消息? – Mark