URLS in GET MVC 4 ASP.NET

本文关键字:ASP NET MVC in GET URLS | 更新日期: 2023-09-27 18:13:09

我有一个要求

得到/Api/客户/1/URL。

所以我修改了

config.Routes.MapHttpRoute(
                 name: "MyApi",
                 routeTemplate: "api/Customers/{action}/{CustID}/{URL}",
                 defaults: new { Controller = "Customers", custID = @"'d+", URL = @"['/'/'w.:?'/'/=&]" }

我也改变了web.config

<httpRuntime targetFramework="4.5" requestPathInvalidCharacters=""/>

当我运行应用程序并输入localhost/Api/Customers/GetDetails/1/http://www.test.com时,

——GetDetails

[System.Web.Http.AcceptVerbs("GET")]
[OutputCache(Location = System.Web.UI.OutputCacheLocation.None, Duration = 0, VaryByParam = "None")]
public void GetDetails(int CustID, string URL_FilePath)
{
    Customer newcust = new Customer();
    newcust.CustID = CustID;
    newcust.URL_FilePath = URL_FilePath;
    Post(newcust);
}

[System.Web.Http.AcceptVerbs("POST")]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public void Post([FromBody]Customer value)
{
        //call database procedure and pass Customer object and commit
        //If exception show error
}

我在'/'应用程序中得到服务器错误。错误从何而来?如何允许url ?

URLS in GET MVC 4 ASP.NET

我找到了几种方法来解决这个问题:

。添加设置到web.config:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

在你的路由配置中使用*作为URL参数:

config.Routes.MapHttpRoute(
    name: "MyApi",
    routeTemplate: "api/Customers/{action}/{CustID}/{*URL_FilePath}",
    defaults: new { Controller = "Customers", custID = @"'d+" , URL = @"['/'/'w.:?'/'/=&]" });

*表示将所有剩余的地址传递给该参数。我在我的机器上测试时发现的问题是,如果您传递完整的url,如

http://localhost/Api/Customers/getDetails/1/http%3A%2F%2Fwww.test.com 

重复斜杠被删除,张贴的值是http:/www.test.com。你可以很容易地更新url,在控制器方法中添加额外的斜杠。我没有调查它是否与浏览器或web服务器设置有关。

第二个选项是不添加URL_FilePath到路由,并将其作为查询字符串参数传递:

routeTemplate: "api/Customers/{action}/{CustID}"

并像这样使用请求:

http://yourservername/Api/Customers/getDetails/1?URL_FilePath=http%3A%2F%2Fwww.test.com. 

在这种情况下,参数值是正确的(所有斜杠都在适当的位置)。在这种情况下,你不需要将runAllManagedModulesForAllRequests设置为true