ASP.NET Web API 中带有可选参数的属性路由 [英] Attribute routing with optional parameters in ASP.NET Web API

查看:46
本文介绍了ASP.NET Web API 中带有可选参数的属性路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Web API 2 属性路由来设置自定义 API.我已经让我的路线工作,以便我的函数被调用,但出于某种原因,我需要传入我的第一个参数才能正常工作.以下是我想要支持的网址:

I'm trying to use Web API 2 attribute routing to set up a custom API. I've got my route working such that my function gets called, but for some reason I need to pass in my first parameter for everything to work properly. The following are the URLs I want to support:

http://mysite/api/servicename/parameter1
http://mysite/api/servicename/parameter1?parameter2=value2
http://mysite/api/servicename/parameter1?parameter2=value2&parameter3=value3
http://mysite/api/servicename/parameter1?parameter2=value2&parameter3=value3&p4=v4

最后 3 个 URL 有效,但第一个显示未在与请求匹配的控制器‘控制器名称’上找到任何操作."

The last 3 URLs work but the first one says "No action was found on the controller 'controller name' that matches the request."

我的控制器如下所示:

public class MyServiceController : ApiController
{
    [Route("api/servicename/{parameter1}")]
    [HttpGet]
    public async Task<ReturnType> Get(string parameter1, DateTime? parameter2, string parameter3 = "", string p4 = "")
    {
        // process
    }
}

推荐答案

Web API 需要显式设置可选值,即使对于可为空的类型...因此您可以尝试设置以下内容,您应该会看到您的第一个请求成功

Web API requires to explicitly set optional values even for nullable types...so you can try setting the following and you should see your 1st request succeed

DateTime? parameter2 = null

这篇关于ASP.NET Web API 中带有可选参数的属性路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆