C# 将JSON传递到.NETAPI
我试图通过在.NET中创建一个[HttpPost]方法,在数据库中插入一个新行,其中包含通过JSON发送的数据。 我正在使用Postman测试API,但我一直遇到相同的问题:C# 将JSON传递到.NETAPI,c#,.net,json,routes,C#,.net,Json,Routes,我试图通过在.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 f
"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},现在它通过了。但是,我得到的用户对象为null。我又错过了什么
用户模型
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:头用于描述请求,而不是实际的请求数据 在正文中发送JSON负载,而不是使用头 因此,将标题
Content-Type
设置为application/json
,并发布json正文:
{
"Email" : "email",
"..." : "..."
}
您不需要在路由路径中包含{json},因为您正在使用HttpPost。只需使用[Route(“api/RegisterController/CreateUser”)]另一个注意事项,如果除您之外的任何人都可以访问此内容,则很容易进行SQL注入。您允许用户直接对您的数据库编写查询。@KiranBeladiya,这很有意义。。但愿我早点意识到这一点。但是,获取用户对象是否正确?我在谷歌上搜索了一下,但这是我找到的。@Xience是的,谢谢。这只是一个虚拟项目开始。我只是对连接后端和前端感兴趣end@MonicaS是的,获取用户对象是正确的。如果您发布的是正确的用户JSON,那么这应该是有效的。