URL Parameter encoding in MVC .NET

二次信任 提交于 2019-12-09 18:13:17

问题


I have a controller in an MVC 4 .NET application that receives a string as a parameter from an URL. This comes from an aspx page redirected to the controller in Route.config.

If I send this value for the parameter in the client: fwdgerhb+bhrth+ftrgbhrt

I get the following value at the server: fwdgerhb bhrth ftrgbhrt

The server is interpreting the URL parameter value as an encoded URL and replaces + by . But it has not been URL encoded. This will occur for other combinations of special chars if they appear in the parameter value.

Is there a config parameter in IIS Server to configure the server to not try to URL-decode this value?

Example Request:

mypage.aspx?value=cat+dog    (NOT ENCODED)

Route Config

static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRouteLowercase(
        name: "MyRouter",
        url: "mypage.aspx",
        defaults: new { controller = "My", action = "DoLog" }
    );
}

The controller:

public class MyController : Controller
{
    [AllowAnonymous]
    public ActionResult DoLog(string value)
    {
        //Here value has "cat dog"
    }
}

回答1:


Yes, MVC automatically URL decodes action parameters, but you can still access the URL encoded version through a query string. As you can see in this question: Is MVC2 ASP.Net URLDecoding automatically?

You can also try to access a server variable named UNENCODED_URL. More information about this scenario can be found here: URL Rewrite Module Configuration Reference




回答2:


You can use the following to grab the query-string manually from the controller:

Request.QueryString.Get("value");

Or, to get it from the view:

Html.ViewContext.HttpContext.Request.QueryString.Get("value");

But honestly, why not just encode the string yourself before you send it through the routing:

HttpUtility.UrlEncode(value);

and then when you get the the value again:

HttpUtility.UrlDecode(value);

So that way you have control of your string


Update

You can also do the following to allow your routeConfig to allow the "+" attribute:

<location path="CustomHttpHandler">
  <system.webServer>
    <security>
      <requestFiltering allowDoubleEscaping="true" />
    </security>
  </system.webServer>
</location>

Here is a question that tells you the ups and downs of turning this on and off: Is Enabling Double Escaping Dangerous?



来源:https://stackoverflow.com/questions/26180572/url-parameter-encoding-in-mvc-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!