Я создал Custom Action Filter
с тремя свойствами, как показано ниже:
public class TrackUser : ActionFilterAttribute, IActionFilter
{
public string BaseUrl { get; set; }
public string Service { get; set; }
public HealthUtil.PageCode Pagecode { get; set; }
public void OnActionExecuting(ActionExecutingContext filterContext)
{
// Some logic to execute
}
}
Я пытаюсь использовать этот фильтр действий клиента с моими действиями, как показано ниже:
[TrackUser(BaseUrl =baseUrl, Service =service1, Pagecode =HealthUtil.PageCode.HealthHome)]
public ActionResult AddLead(leadViewModel leaddata)
{
}
Свойство baseUrl
определено в классе baseUrl
как baseUrl
ниже:
public static string baseUrl
{
get { return "http://localhost:52985/api/"; }
//set { baseUrl = value; }
}
Проблема в том, что я не могу передать baseUrl
в фильтр действий. Я получаю следующее сообщение об ошибке:
Аргумент атрибута должен быть константным выражением, выражением typeof или выражением создания массива типа параметра атрибута
Пожалуйста, помогите мне решить эту проблему.
EDIT baseUrl
в baseUrl
должен быть свойством, поскольку более поздний код будет читать его из App.Config.
Вы можете определить метод в своем ParentController
следующим образом:
public class ParentController : Controller
{
public string GetUrl()
{
return ConfigurationManager.AppSettings["AppUrl"];
}
}
Затем в вашем классе фильтра вы можете вызвать метод родительского контроллера, чтобы получить URL-адрес:
public class TrackUser : ActionFilterAttribute, IActionFilter
{
public string BaseUrl { get; set; }
public string Service { get; set; }
public void OnActionExecuting(ActionExecutingContext filterContext)
{
// Some logic to execute
var controller = filterContext.Controller as ParentController;
if (controller != null)
{
var url = controller.GetUrl();
// Use it here
}
}
}
Надеюсь, это поможет, последуйте за вопросом приветствуем!
Попробуйте изменить определение свойства baseUrl, как показано ниже в классе ParentConroller.
public const string baseUrl = "http://localhost:52985/api/";
Добавить ниже код для OnActionExecuting
метода TrackUser
класса
public void OnActionExecuting(ActionExecutingContext filterContext)
{
//get hold of the controller
var controller = filterContext.Controller as ParentController;
//assign the BaseUrl property from tye ParentController and use it as required
BaseUrl = controller.BaseUrl;
// Some logic to execute
}
В ParentController' class Change the
ParentController ParentController' class Change the
baseUrl ', как показано ниже,
//get the URL from App.Config and assign to baseUrl
public string baseUrl = "http://localhost:52985/api/";
Обновите AddLead
Action, удалив свойство BaseUrl
, так как он обрабатывается в TrackUser
фильтра действия TrackUser
[TrackUser(Service = service1, Pagecode = HealthUtil.PageCode.HealthHome)]
public ActionResult AddLead(leadViewModel leaddata)
{
//do something with the action
}'