I am working on an MVC 5 web application. I have the following layers:-
- Views
- Controller classes.
- Repository classes, which are being referenced inside the controller classes.
- Model classed
- Entity framework DB context.
now i have the following requirement:-
Inside some action methods I want my application to be sending some API calls (using WebClient()) to 3rd party application.
Where the API calls will almost be the same for all the action methods, except for the Description parameter. Now I can have this shared logic inside my repository class, and reference it from my action methods. But as I know that repository class should not expose or reference WebClient() or similar web classes, as repository should deals with databases and model classes only.
So I am not sure what is the best place to manage shared WebClient calls ? so from the action method I only call the shared class and pass the description field ?
For example here is a sample of an action method which directly contain the web client :-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Server s)
{
if (ModelState.IsValid)
{
try
{
//code goes here....
XmlDocument doc = new XmlDocument();
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
query["username"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiUserName"];
query["password"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiPassword"];
query["assetType"] = controllername;
query["operation"] = "UpdateAsset";
query["assetName"] = s.RESOURCENAME;
query["description"] = s.DESCRIPTION;
//code goes here
var url = new UriBuilder(apiurl);
url.Query = query.ToString();
try
{
string xml = client.DownloadString(url.ToString());
doc.LoadXml(xml);
updatestatus = doc.SelectSingleNode("/operation/operationstatus").InnerText;
}
catch (WebException ex)
{
ModelState.AddModelError(string.Empty, "Error occurred:" + ex.InnerException.Message);
}
}
}
}
}
now i do not want to be adding the same WebClient method on multiple action methods,, but rather to have the WebClient() on a shared class, and reference it from the related action methods .