我已經使用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
並運行此查詢,我發現了以下結果
我不知道有什麼真正的問題,我堅持它。
任何幫助將不勝感激。
@EpicKip實際上在代碼中有一個'Environment.NewLine',它也是錯誤發生的地方。 – Dirk