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