2016-02-12 50 views
4

我通過ASP.NET MVC創建了一個簡單的API 4文件路徑:ASP.NET無法解析xml!檢查

public class ActionController : ApiController 
{ 
    [WebMethod] 
    public string getCommunities() 
    { 
     try 
     { 
      MethodClass method = new MethodClass(); 
      return method.getCommunities(); 
     } 
     catch(Exception ex) 
     { 
      return ex.Message.ToString(); 
     } 
    } 
} 

正試圖調用方法類,這個方法:

public string getCommunities() 
{ 
    return "bbb"; 
} 

,但不管是什麼原因,我得到這個錯誤:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">cannot parse xml! Check file path</string> 

我試着用搜索引擎的錯誤,但一無所獲,也沒有人見過這個錯誤?我該如何解決它?

+1

WebMethod?爲什麼在這裏? –

+0

,因爲我正在計劃通過ajax使用此代碼 – user979331

+0

[WebMethod]對於MVC應用程序不是必需的。頁方法是老派在代碼後面(aspx.cs)頁面做的方式... –

回答

5

正如評論中指出的那樣,您正在錯誤的地方尋找您的錯誤。 method.getCommunities()拋出一個錯誤消息「無法解析XML!檢查文件路徑」。

使用谷歌搜索您的error在我看來,你正在拋出一個自定義異常:在你的代碼中搜索該字符串可能指向你正確的地方。

作爲概念的快速證明,我更改了由Visual Studio Web API模板生成的標準API。

public string Get(int id) 
     { 
      try 
      { 
       var t = 0; 
       var i = 1/t; 
       return "bbb"; 
      } 
      catch { return "ABBA"; } 
     } 

這正好返回自定義錯誤消息爲XML字符串

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">ABBA</string> 
2

我試圖通過如下在ASP.Net MVC 4模板創建簡單ActionController.cs複製你提到的情況:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using System.Web.Services; 

namespace MvcApiApplicationTrial1.Controllers 
{ 
    public class ActionController : ApiController 
    { 
    [WebMethod] 
    public string getCommunities() { 
     try { 
     MethodClass method = new MethodClass(); 
     return method.getCommunities(); 
     } catch (Exception ex) { 
     return ex.Message.ToString(); 
     } 
    } 
    } 

    public class MethodClass 
    { 
    public string getCommunities() { 
     return "bbb"; 
    } 
    } 
} 

然後在網絡瀏覽器(Chrome)中使用以下URL調用它:

http://localhost:56491/api/Action/getCommunities 

並獲得以下正確結果:

enter image description here

如果要聲明,定義,並調用正確的事情,你的代碼應該有沒有問題都沒有。

因此,我建議您再次檢查您的聲明,定義以及您對相關控制器/方法的調用。你的問題可能在別的地方。

而且由於錯誤似乎是一個自定義錯誤,從單獨發佈的代碼判斷,很可能該問題存在於getCommunities方法的某處。檢查方法,嘗試找到「無法解析xml!」文字在那裏。另外,但不太可能,錯誤在MethodClass構造函數中。同樣的事情,請檢查您的MethodClass,嘗試找到「無法解析xml!」文本。

至於你在你的問題中發佈的情況,我沒有發現任何問題。

try和「bbb」之間的其他內容也可能是創建錯誤的來源。如果try區塊中有更多內容,檢查錯誤文本將是我的第一步,並且我不確定可能實際生成錯誤的位置。

0

在Global.asax.cs中應該把代碼波紋管:

GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());

和WebApiConfig代碼波紋管:

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(新MediaTypeHeaderValue( 「文本/ XML」)); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t = > t.MediaType ==「application/xml」);