Mat*_*ser 4 c# asp.net-web-api asp.net-web-api-routing
我想根据特定json参数的值将请求路由到不同的操作.
例如,给定以下json数据:
{
type: "type1",
type1data: "type1value"
}
Run Code Online (Sandbox Code Playgroud)
和
{
type: "type2",
type2data: "type2value"
}
Run Code Online (Sandbox Code Playgroud)
我希望能在我的ApiController上有两个不同的动作:
void CreateType1(string type1data)
{
// ...
}
void CreateType2(string type2data)
{
//...
}
Run Code Online (Sandbox Code Playgroud)
这样的事情怎么办?
更新:
如果可能,我想要相同的网址.有点像/objects/create.
我宁愿使用自定义的ApiControllerActionSelector.
public class MyActionSelector : ApiControllerActionSelector
{
public override HttpActionDescriptor SelectAction(
HttpControllerContext context)
{
HttpMessageContent requestContent = new HttpMessageContent(
context.Request);
var json = requestContent.HttpRequestMessage.Content
.ReadAsStringAsync().Result;
string type = (string)JObject.Parse(json)["type"];
var actionMethod = context.ControllerDescriptor.ControllerType
.GetMethods(BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(m => m.Name == "Create" + type);
if (actionMethod != null)
{
return new ReflectedHttpActionDescriptor(
context.ControllerDescriptor, actionMethod);
}
return base.SelectAction(context);
}
}
Run Code Online (Sandbox Code Playgroud)
这是模型.我给了它一个奇怪的名字Abc.
public class Abc
{
public string Type { get; set; }
public string Type1Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是动作方法.
public void Createtype1(Abc a)
{
}
Run Code Online (Sandbox Code Playgroud)
最后,插入动作选择器.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Services.Replace(typeof(IHttpActionSelector),
new MyActionSelector());
}
}
Run Code Online (Sandbox Code Playgroud)
如果现在POST到http:// localhost:port/api/yourapicontroller,则根据JSON中类型字段中的值,将选择操作方法Create*.
| 归档时间: |
|
| 查看次数: |
1915 次 |
| 最近记录: |