Using a dash (-) in ASP.MVC parameters

后端 未结 5 1461
失恋的感觉
失恋的感觉 2020-12-05 08:26
<% using (Html.BeginForm(\"SubmitUserName\")) { %>
    
    
<         


        
5条回答
  •  醉梦人生
    2020-12-05 09:01

    I found this answer helpful, but I don't know exactly how the provided example helps. It appears to just "rename" a value that the binder all ready provided.

    In my case, I was being posted to by an external service that would post something like "body-plain" and I could not control the name. So I modified this sample to look like this:

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class ParameterNameMapAttribute : ActionFilterAttribute
    {
        public string InboundParameterName { get; set; }
        public string ActionParameterName { get; set; }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            object value = filterContext.RequestContext.HttpContext.Request[InboundParameterName];
    
            if (filterContext.ActionParameters.ContainsKey(ActionParameterName))
            {
                filterContext.ActionParameters[ActionParameterName] = value;
            }
            else
            {
                throw new Exception("Parameter not found on controller: " + ActionParameterName);
            }
        }
    }
    

    This actually takes in the parameter "body-plain" for example and maps it to an ActionParameter I defined on my controller. Like so:

    [ParameterNameMap(InboundParameterName = "body-plain", ActionParameterName = "bodyPlainText")]
        [ParameterNameMap(InboundParameterName = "Thread-Topic", ActionParameterName = "alternateSubject")]
        public HttpStatusCodeResult Process(string token, string timestamp, string signature, string subject, string sender, string recipient, string bodyPlainText, string alternateSubject)
        {
    

提交回复
热议问题