我尝试通过连接mysql创建一个asp.net webapi。添加了所有mysql引用。我尝试http://localhost:22522/api/Values/1
,然后得到一个错误,如下图所示。我不知道哪里出错了?谁能帮我。
webapi config:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using MySql.Data.MySqlClient;
namespace webapp
{
public static class WebApiConfig
{
public static MySqlConnection conn()
{
string conn_string = "server=localhost; port=8080; database=all_users; Uid=root; Pwd =123;";
MySqlConnection conn = new MySqlConnection(conn_string);
return conn;
}
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
价值控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MySql.Data.MySqlClient;
namespace webapp.Controllers
{
public class ValuesController : ApiController
{
public class result
{
public string username { get; set; }
public string password { get; set; }
public string error { get; set; }
public result(string username, string password, string error)
{
this.username = username;
this.password = password;
this.error = error;
}
}
// GET api/values/5
public List<result> Get(int id)
{
MySqlConnection conn = WebApiConfig.conn();
MySqlCommand query = conn.CreateCommand();
query.CommandText = "SELECT username, password From users";
var result = new List<result>();
try
{
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
result.Add(new result(null, null, ex.ToString()));
}
MySqlDataReader fetch_query = query.ExecuteReader();
while (fetch_query.Read())
{
result.Add(new result(fetch_query["username"].ToString(), fetch_query["password"].ToString(), null));
}
return result;
}
}
}
的web.config:
<connectionStrings>
<add name="conn_string" connectionString="server=localhost; port:8080; User Id=root;database=all_users;password=123" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
DB:
错误: