Vin*_*ows 1 c# asp.net-mvc asp.net-web-api
我正在使用ASP.NET Web API和控制器类来处理来自客户端的JSON数据.我遇到过一个控制器需要多个Put方法的情况.
例:
一个我的客户,我可以
var box = {size:2,color:'red',height:45,width:12}
Run Code Online (Sandbox Code Playgroud)
现在,如果我想更新整个盒子对象,我可以做一个
public void Put(Box box)
{
}
Run Code Online (Sandbox Code Playgroud)
好的,我得到了这么多.
但我需要能够更新框的单个值,如下所示:
public void Put(int id, width value)
{
}
public void Put(int id, height value)
{
}
public void Put(int id, color value)
{
}
Run Code Online (Sandbox Code Playgroud)
如何从我的.net c#控制器中映射额外的Put动词?
我将为我刚刚创建的赏金添加更多代码.我需要有人向我展示如何制作我正在提供工作的代码.我需要将多个方法映射到一个httpVERB PUT.原因是我需要微服务器上的更新项目.就像名字一样,我不想通过线路发送大型对象来更新一个字段,因为我的程序也将连接到移动设备.
---这段代码不起作用,只返回PutName而且从不返回PutBrand.我已经以你能想象到的任何方式切换了签名.
[AcceptVerbs("PUT")]
[ActionName("PutBrand")]
public HttpResponseMessage PutBrand(int id, int val)
{
return Request.CreateResponse(HttpStatusCode.Created, "Brand");
}
[AcceptVerbs("PUT")]
[ActionName("PutName")]
public HttpResponseMessage PutName(IDString idString)
{
return Request.CreateResponse(HttpStatusCode.Created, "Name");
}
public class IDString
{
public IDString() { }
public int ID { get; set; }
public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
- - 客户
$.ajax(
{
url: "/api/project",
type: "PUT",
data: JSON.stringify({ id: 45, val:'xxx' }),
contentType: "application/json",
success: function (result) {
}
});
Run Code Online (Sandbox Code Playgroud)
---路线配置
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Run Code Online (Sandbox Code Playgroud)
提出的解决方案
$.ajax(
{
url: "/api/project?a=name",
type: "PUT",
$.ajax(
{
url: "/api/project?a=brand",
type: "PUT",
$.ajax(
{
url: "/api/project?a=size",
type: "PUT",
Run Code Online (Sandbox Code Playgroud)
当然我会在a = myJavaScriptVariable的位置使用变量
public HttpResponseMessage Put(Project project)
{
string update = HttpContext.Current.Request.QueryString["a"];
switch (update)
{
case "name":
break;
case "brand":
break;
case "size":
break;
default:
break;
}
return Request.CreateResponse(HttpStatusCode.Accepted);
}
Run Code Online (Sandbox Code Playgroud)
HTTP动词不是动作的名称,它是一个注释.
这样,您的控制器应如下所示:
[VERB]
public ActionResult SomeMeaningfulName(ARGUMENTS)
{
//...
}
Run Code Online (Sandbox Code Playgroud)
当动词或者是HttpDelete,HttpPost,HttpPut或者HttpGet
希望这可以帮助.
问候
更新:我的上述答案适用于ASP.NET MVC应用程序.但是,如果我们讨论的是WebAPI应用程序,那么还有另一个选项可以设置动作的动词:WebAPI使用一种将动作名称理解为动词的约定,只要它是一个有效的HTTP动词即可.该操作甚至可能具有有意义的名称,但必须以动词开头.这篇文章的更多信息.
感谢@Anand指出这一点(并努力让我理解=)).
| 归档时间: |
|
| 查看次数: |
1594 次 |
| 最近记录: |