2017-09-26 90 views
0

我已經使用MySQL數據庫在visual studio 2015中創建了一個API。我有兩種GET方法。一個獲取所有記錄,另一個通過ID獲取記錄。第一種方法是完美的,但第二種方法引發了一個例外。值' r n'的格式無效。「,」ExceptionType「:」System.FormatException

{"Message":"An error has occurred.","ExceptionMessage":"The format of value '\r\n' is invalid.","ExceptionType":"System.FormatException","StackTrace":" at System.Net.Http.Headers.MediaTypeHeaderValue.CheckMediaTypeFormat(String mediaType, String parameterName)\r\n at System.Net.Http.Headers.MediaTypeHeaderValue..ctor(String mediaType)\r\n at System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage request, HttpStatusCode statusCode, T value, String mediaType)\r\n at WebServiceMySQL.Controllers.MetersInfoController.Get(Int32 id) in E:\\Work\\NEW API\\WebServiceMySQL\\WebServiceMySQL\\Controllers\\MetersInfoController.cs:line 33"} 

下面是我的代碼

public partial class meters_info_dev 
{ 
    public int id { get; set; } 
    public string meter_msn { get; set; } 
    public string meter_kwh { get; set; } 
} 

控制器

public MeterEntities mEntities = new MeterEntities(); 

    // GET all 
    public HttpResponseMessage Get() 
    { 
     try 
     { 
      return Request.CreateResponse(HttpStatusCode.Found, mEntities.meters_info_dev.ToList()); 
     } 
     catch (Exception ex) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); 
     } 
    } 

    // GET by ID 
    public HttpResponseMessage Get(int id) 
    { 
     try 
     { 
      return Request.CreateResponse(HttpStatusCode.Found, mEntities.meters_info_dev.SingleOrDefault(m => m.id == id), Environment.NewLine); 
     } 
     catch (Exception ex) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); 
     } 
    } 

WebApiConfig

// Web API configuration and services 
     // Configure Web API to use only bearer token authentication. 
     config.SuppressDefaultHostAuthentication(); 
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 

     config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json")); 
     config.Formatters.Remove(config.Formatters.XmlFormatter); 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 


     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

在調試Get(int id)部分,我發現了一個查詢是

SELECT Extent1.id, Extent1.meter_msn, Extent1.meter_kwh FROM meters_info_dev AS Extent1 

並運行此查詢,我發現了以下結果

enter image description here

我不知道有什麼真正的問題,我堅持它。

任何幫助將不勝感激。

+1

@EpicKip實際上在代碼中有一個'Environment.NewLine',它也是錯誤發生的地方。 – Dirk

回答

4

你逝去的CreateResponse()Environment.NewLine作爲最後一個參數和換行擴展到字符串「\ r \ n」。最後一個參數應該是配置,媒體類型或格式化程序或根本不傳遞。上面幾行你用兩個參數使用它,它的工作原理。檢查文檔here

+0

是的,這是我犯的錯誤。 – faisal1208

相關問題