【发布时间】:2017-06-15 13:26:34
【问题描述】:
我正在尝试在 .NET 中创建一个 [HttpPost] 方法,该方法在数据库中插入一个新行,其中包含通过 JSON 发送的数据。 我正在使用 Postman 测试 API,但我一直遇到同样的问题:
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:13489/api/RegisterController/CreateUser/'.",
"MessageDetail": "No type was found that matches the controller named 'RegisterController'."
但是,当我尝试只传递一个字符串,而不是一个用户对象或 Json 格式的字符串时,它工作得很好。我想我没有传递正确的对象类型? 路由配置如下
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
这里是post方法:
[Route("api/RegisterController/CreateUser/{json}")]
[HttpPost]
public HttpResponseMessage CreateUser( User json)
{
// JObject jObject = JObject.Parse(json);
string sql = "INSERT INTO user(Email, Password, Name, DateOfBirth, profile_pic) VALUES('" + json.Email + "','" +
json.Password + "','" +json.Name + "','"+json.DateOfBirth+"','randomurl');";
MySqlCommand command = new MySqlCommand(sql, _db.Connection);
try
{
_db.Connection.Open();
command.ExecuteNonQuery();
return Request.CreateErrorResponse(HttpStatusCode.Conflict, "User registerd");
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
return Request.CreateErrorResponse(HttpStatusCode.Conflict, exception.Message);
}
finally { _db.Connection.Close(); }
}
更新: 从路径中删除了 {json},现在它通过了。但是,我得到的 User 对象为空。我又错过了什么?
用户模型
public class User
{
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string DateOfBirth { get; set; }
public string ProfilePic { get; set; }
}
【问题讨论】:
-
您不需要在路由路径中包含 {json},因为您使用的是 HttpPost。仅使用 [Route("api/RegisterController/CreateUser")]
-
另外注意,如果除了你之外的任何人都可以访问它,那么它很容易发生 SQL 注入。您允许用户直接针对您的数据库编写查询。
-
@KiranBeladiya 这是有道理的。希望我能早点意识到这一点。但是,获取 User 对象是否正确?我一直在谷歌搜索,但这是我发现的。
-
@xiience 是的,谢谢。这只是一个入门的虚拟项目。我只是对将后端连接到前端感兴趣
-
@MonicaS 是的,获取用户对象是正确的。如果您发布了正确的用户 JSON,这应该可以工作。