0

我在我的 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}"
4

2 回答 2

3

您需要更改webapi route,因为它期望用户作为最后一个参数。您可以将其设置为 { 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}"

看看routes here

于 2013-10-25T05:48:18.703 回答
1

你的 JSON

      "{"UserLoginName": "steve ","UserID":-2147483637,"IsDeleted":false}"

尝试这个

  {"UserLoginName": "steve","UserID":"-2147483637","IsDeleted":"false"}

为 Web 发布数据的代码

    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/

于 2013-10-25T05:14:52.630 回答