我无法在我的web api项目中将JSON复杂对象发送到我的用户控件。我一直得到404.我有一些控制工作(任何路由/ api / {control} / {action} / {id})但没有路由(/ api / {control} / {action} / {user })将为我工作。任何帮助将不胜感激。
路线配置
config.Routes.MapHttpRoute(
name: "UserApi",
routeTemplate: "api/{controller}/{action}/{User}");
用户对象
public class User
{
public String UserLoginName { get; set; }
public int UserID { get; set; }
public bool IsDeleted { get; set; }
}
控制器
[HttpPost]
public Models.User AddUser([FromBody]User targetUser)
{
var userDTO = new UserDTO();
var businessUser = userDTO.GetNewBusinessObject(targetUser);
return userDTO.GetNewServiceObject(businessUser.Add());
}
json请求
POST http://localhost:54002/api/user/AddUser HTTP/1.1
User-Agent: Fiddler
Host: localhost:54002
content-length: 69
content-type: application/json;charset=utf-8
"{"UserLoginName": "steve ","UserID":-2147483637,"IsDeleted":false}"
答案 0 :(得分:3)
您需要更改 webapi路径,因为它希望将用户作为最后一个参数。您可以将此设置为{Id
}作为可选项,就像默认值一样。
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
另外,请确保API控制器为UserController
。
当你从Fiddler发帖时,JSON应该是这样的......
{"UserLoginName": "steve", "UserID": -2147483637, "IsDeleted": false }
而不是......
"{"UserLoginName": "steve ","UserID":-2147483637,"IsDeleted":false}"
答案 1 :(得分:1)
你的Json
"{"UserLoginName": "steve ","UserID":-2147483637,"IsDeleted":false}"
试试这个
{"UserLoginName": "steve","UserID":"-2147483637","IsDeleted":"false"}
发布网络数据的代码
User ObjUs = new User();
ObjUs.UserLoginName = "steve";
ObjUs.UserID = -2147483637;
ObjUs.IsDeleted = false;
System.Web.Script.Serialization.JavaScriptSerializer ObjSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
object sSeralize = ObjSerializer.Serialize(ObjUs);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:54002/api/user/AddUser HTTP/1.1");
byte[] data = Encoding.UTF8.GetBytes(sSeralize.ToString()); // Input Data
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/json";
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
StreamReader result = new StreamReader(resp.GetResponseStream());
if(result !=null)
{
if(!string.IsnullorEmpty(result.ReadToEnd()))
{
String sResponseData = result.ReadToEnd();
}
}
public class User
{
public String UserLoginName { get; set; }
public int UserID { get; set; }
public bool IsDeleted { get; set; }
}
检查此站点以创建结构化Json字符串:http://json.parser.online.fr/