【问题标题】:Create a custom Http method创建自定义 Http 方法
【发布时间】:2016-08-07 04:05:13
【问题描述】:

是否可以通过重写HttpMethodAttribute 类并指定我们自己的supportedMethods 来创建我们自己的HTTP 方法?

实际上,视情况而定,我们需要将View作为完整的视图与_Layout一起返回,有时我们只需要返回该视图的PartialView即可。所以我的想法是放置一个自定义属性,例如[HttpPartial],因此客户端会根据请求中使用的方法告诉它是想要完整视图(GET 方法)还是部分视图(PARTIAL 方法)。

【问题讨论】:

    标签: asp.net-core http-method


    【解决方案1】:

    是的,这对于 API 来说是可能的。您可以look at how the HttpGetAttribute is implemented,并为自定义方法滚动自己的方法,将“get”替换为“foo”:

    /// <summary>
    /// Identifies an action that supports the HTTP FOO method.
    /// </summary>
    public class HttpFooAttribute : HttpMethodAttribute
    {
        private static readonly IEnumerable<string> _supportedMethods = new[] { "FOO" };
    
        /// <summary>
        /// Creates a new <see cref="HttpFooAttribute"/>.
        /// </summary>
        public HttpFooAttribute()
            : base(_supportedMethods)
        {
        }
    
        /// <summary>
        /// Creates a new <see cref="HttpFooAttribute"/> with the given route template.
        /// </summary>
        /// <param name="template">The route template. May not be null.</param>
        public HttpFooAttribute(string template)
            : base(_supportedMethods, template)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }
        }
    }
    

    然后将其应用于您的 API 操作方法:

    [Route("Bar")]
    public class BarApiController : Controller
    {
        [HttpFoo("/"]
        public IActionResult Foo()
        {
            return Ok("Foo");
        }
    }
    

    现在您可以请求FOO https://your-api:44312/bar/。

    这对于返回视图的操作不太有用,例如通过超链接和表单any HTML-rendering user agent only lets the user initiate GET or POST requests。

    您可以通过XMLHttpRequest 或fetch() 发送更多方法,但这需要更多文档和客户端自定义。

    不要破坏或阻碍网络,不要为您的应用程序逻辑发明新的 HTTP 方法。只需使用查询字符串参数或将其发送到您的正文中:&amp;renderAsPartial=true、{ "renderAsPartial": true }。

    有关现有方法,请参阅the IANA's Hypertext Transfer Protocol (HTTP) Method Registry,有关如何注册新 HTTP 方法,请参阅RCF 7231 section 8.1。

    【讨论】:

    • 如果 HTML-rendering 用户代理是 Ajax 调用,我可以指定 Http 方法吗?
    • 如果您不喜欢使用查询参数,也可以设置像 X-Request-View: partial 这样的标题
    • 谢谢大家,我们听从了您的建议。我们使用了 ASP.NET Core 的所有功能,因此我们创建了一个中间件来分析请求,并通过我们所有应用程序中可用的单例提供信息(如果它是 Ajax 调用)。
    • 如果我想在我的api中实现LINK/UNLINK动词怎么办? asp.net core 不允许these methods
    • @Сергей 查看更新。
    【解决方案2】:

    相反,我会建议类似于提琴手的东西......

    【讨论】:

    • 我不是在寻找一个工具,而是一个想法或方法告诉服务器端:使用我的部分视图或使用我的完整视图,所有这些都只使用 Http 请求。
    猜你喜欢
    • 2015-02-09
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 2011-01-02
    • 2015-06-21
    • 2014-02-14
    • 2018-02-04
    • 2015-06-04
    相关资源
    最近更新 更多