gpt4 book ai didi

c# - Web Api 路由处理程序更改路由数据

转载 作者:太空宇宙 更新时间:2023-11-03 12:51:12 33 4
gpt4 key购买 nike

在 web api 路由中,我创建了以下路由和路由处理程序。

我试图拦截请求并在它到达实际方法之前更改一些路由数据。

但是下面的代码并没有像我预期的那样工作,当运行并向 api 发出请求时,它返回 404 没有找到提供 Controller 名称匹配请求的路由

这真的可以改变路线数据吗?我觉得我接近解决方案但遗漏了一些东西。

下面是我的代码:

public class CustomHander : DelegatingHandler {
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {

var routeData = request.GetRouteData();
var subroutes = (IEnumerable<IHttpRouteData>)routeData.Values["MS_SubRoutes"];
var route = subroutes.First();

var msSubRoutes = new HttpRouteValueDictionary();

var httpRouteData = new HttpRouteData(route.Route);

foreach (var r in route.Values) {
httpRouteData.Values.Add(r.Key, r.Value.ToString().Replace("|", "/"));
}

msSubRoutes.Add("MS_SubRoutes", httpRouteData);
var newRoute = new HttpRouteData(routeData.Route, msSubRoutes);

request.SetRouteData(newRoute);
var test = request.GetRouteData();

var resp = await base.SendAsync(request, cancellationToken);
return resp;
}
}

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, controller = "Vehicles" }
);

config.MessageHandlers.Add(new CustomHander());
}
}

如果我删除下面的代码行,那么它会正常工作,但显然不会更改路由数据。

request.SetRouteData(newRoute);

Controller 上的操作结果示例:

[Route("api/Makes")]
[HttpGet]
public IHttpActionResult Makes()
{
using (var db = new eCatEntities())
{
var makes = db.VEHICLEs.Select(p => new { TEXT = p.VEHI_MAKE }).Distinct().OrderBy(p => p.TEXT);

return Json(makes.ToList());
}
}

[Route("api/Models/{make}")]
[HttpGet]
public IHttpActionResult Models(string make)
{
using (var db = new eCatEntities())
{
var models = db.VEHICLEs.Where(p => p.VEHI_MAKE == make.Replace("|", "/")).Select(p => new { TEXT = p.VEHI_MODEL, p.VEHI_ALPHASORT }).Distinct().OrderBy(p => p.VEHI_ALPHASORT);

return Json(models.ToList());
}
}

一个示例 url 是:

http://domain:port/api/Makes
http://domain:port/api/Models/Jaguar|Daimler

最佳答案

扩展路由的扩展点是IHttpRoute(或其默认的具体实现HttpRoute)。处理程序是一个较低级别的对象,它没有生成传出路由的能力(如果您将 / 放在路由值中,您肯定需要解决这个问题)。

public class ReplacePipeHttpRoute : System.Web.Http.Routing.HttpRoute
{
public ReplacePipeHttpRoute(string routeTemplate, object defaults)
: base(routeTemplate, new HttpRouteValueDictionary(defaults))
{ }

// OPTIONAL: Add additional overloads for constraints, dataTokens, and handler

// Converts | to / on incoming route
public override IHttpRouteData GetRouteData(string virtualPathRoot, System.Net.Http.HttpRequestMessage request)
{
var routeData = base.GetRouteData(virtualPathRoot, request);

// RouteData will be null if the URL or constraint didn't match
if (routeData != null)
{
var newValues = new HttpRouteValueDictionary();
foreach (var r in routeData.Values)
{
newValues.Add(r.Key, r.Value.ToString().Replace("|", "/"));
}
routeData = new HttpRouteData(this, newValues);
}

return routeData;
}

// Converts / to | on outgoing route (URLs that are generated from WebApi)
public override IHttpVirtualPathData GetVirtualPath(System.Net.Http.HttpRequestMessage request, IDictionary<string, object> values)
{
var newValues = new Dictionary<string, object>();
if (values != null)
{
foreach (var r in values)
{
// Encode pipe as outlined in: http://www.tutorialspoint.com/html/html_url_encoding.htm
newValues.Add(r.Key, r.Value.ToString().Replace("/", "%7c"));
}
}

return base.GetVirtualPath(request, newValues);
}
}

用法

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.Add(
name: "DefaultApi",
route: new ReplacePipeHttpRoute(
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, controller = "Vehicles" })
);
}
}

NOTE: You might want to reconsider using a pipe character in your URLs.

关于c# - Web Api 路由处理程序更改路由数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35460198/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com