值'\ r \ n'的格式无效。“,”ExceptionType“:”System.FormatException

时间:2017-09-26 11:28:02

标签: c# mysql linq rest asp.net-web-api2

我使用MySQL数据库在visual studio 2015中创建了一个API。我有两种GET方法。一个获取所有记录,另一个获取ID记录。第一种方法是完美的,但第二种方法引发了异常。

{"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 个答案:

答案 0 :(得分:4)

您将此Environment.NewLine作为CreateResponse()的最后一个参数传递,NewLine将扩展为字符串'\ r \ n'。最后一个参数应该是配置,媒体类型或格式化程序,或者根本不传递。你上面几行没有使用它有两个参数,它的工作原理。查看文档here