MVC Rendering (RenderPartial, RenderAction) Html from another MVC Application - c#

I am working in an environment with many teams who are responsible for specific content on pages. Each team is sharing specific information (common class libraries, and master pages) that each are going deliver different types of content.
Is it possible for an MVC application to do something similar to RenderPartial and pass a model to another MVC application Controller/Action to return content?
So the code for this might look like:
(http://www.mydomain.com/Home/Index)
<% Html.RenderAction("ads.mydomain.com", "Home", "Index", AdModel) %>
Maybe this is not a good idea as another thread has to spin up to server a partial view?

No, RenderPartial/RenerAction can only load views that it can access via reflection, not via HTTP requests to external resources.
If the MVC app for 'ads.mydomain.com' is available to you at compile them then you can utilise its resources via Areas, however it won't pickup the changes if they release a new version to the 'ads.mydomain.com' website without you getting their latest assembly and re-compiling and deploying your app as well.
You can do similar stuff with AJAX where you can load a fragment from another site, however it wouldn't be done server side, and would require the client to have javascript enabled. Also the model would need to be converted to JSON and posted to the request, so its a bit of a hacky solution.
You could write an extension method (lets call it Html.RenderRemote) which does all the work for you of creating an http connection to the target and requests the URL. You'd have to serialize the model and send it as part of the request.
public static string RenderRemote(this HtmlHelper, string url, object model)
{
// send request to 'url' with serialized model as data
// get response stream and convert to string
// return it
}
You could use it as :
<%= Html.RenderRemote('http://ads.mydomain.com', Model');
You wouldn't be able to take advantage of the routes on the remote domain, so you'd have to construct the literal URL yourself, which means if they change your routing rules your URL won't work anymore.

In principal yes, though your question is a little vague.
Have a look at "portable areas" within MvcContrib on codeplex. This technique allows separate teams to develop separate MVC apps that would then be orchestrated by a central application.

Related

how does host differentiate MVC request and Web API request

I'm new to asp.net mvc and web api. I'm reading a book which says:
ASP.NET MVC uses: System.Web.HttpRequest
and Web API Equivalent is System.Net.Http.HttpRequestMessage
and below is a picture that describes the request and result flow of web api
So my question is, how does hosting environment(which will typically be IIS) know that it should create a HttpRequestMessage object to represent the request from the client? I mean if the application is a MVC application, IIS should create a HttpRequest object instead of HttpRequestMessage, so how does IIS know which one to create?
As you can see from the picture you posted, the HttpRequestMessage exists only inside the "hosting" environment, web browser client does not know anything about that.
In the "hosting" world, IIS app pool is running the code you have built and deployed which knows very well wich framewok you are using as your code also contains the using assemblies you listed, System.Web... or System.Net...
Consider that even if you have shown separation between hosting, Controller and Action, all of that is running in same App Pool in IIS which, again, runs your code so knows what it is about as your IL assemblies were built from your specific source code.
I am not sure if I understand your question but this might be what you're looking for:
I mean if the application is a MVC application, IIS should create a
HttpRequest object instead of HttpRequestMessage, so how does IIS know
which one to create?
You must remember how you differentiate between a normal MVC Controller and a Web API Controller...
WebAPI Controllers enforces this annotation [ApiController] and must inherits from ControllerBase:
[ApiController]
public class PeopleController : ControllerBase {
//Your API methods here
}
A normal MVC Controller only inherits from Controller base class:
public class PeopleController : Controller {
//Your Action methods here...
}
Those already create configuration for your APP which becomes easier for you Hosting environment to know what is going and what to return when.
I hope you find this helpful.

Can a asp.net MVC controller class return Action Method and Json both?

Thanks for your time , I have a simple question, in an asp.net MVC application, inside controllers is it possible that along with some methods returning View (ActionMethods) other could act as (or return) Json as a Web API (could be called from external apps).
Just trying to do a proper separations, hence trying to understand.
Thanks much.
You can make an action function like an API. Try something like the this.
// Controller/Action
[HttpGet]
public ActionResult IAmSpecial()
{
if (Request.IsAjaxRequest())
{
string[] objects = new string[] { "Foo", "Bar" };
return Json(objects);
}
return View();
}
This will return the IAmSpecial view if you browse to {domain}/{Controller}/IAmSpecial while it will return a JSON result if you use an AJAX Http Get request on the same url.
while it is possible to have controller methods which return Json data only, there are a number of considerations when you want to expose that data outside of the UI app.
Since you have an MVC app, I expect you have users and a way to login. Your controllers would more than likely be secured in some way, which works for the internal users of the application. Now you want to add one method which effectively becomes an API, available outside of the application and calls to it will have to be authenticated somehow.
What I would suggest is to split this up. You can create a separate project, which is a WebAPI one, in the same solution. The code which prepares the data can live in a class library you can then reference in both your MVC and WebAPI projects.
Your MVC app can call it and then return a view with that data, the WebAPI calls it and simply returns the data. You can now decide on a way of securing your API, maybe using Identity Server or some other way and you can keep adding things to it, without affecting the UI layer.
Your second option is to make the MVC app use the API when it needs to retrieve data, so both your public clients and UI use the same thing.
Whichever option you use, the idea is to not duplicate anything and at the same time provide the security layers you need.

AngularJS - Get url in Server side in Application_BeginRequest

I am building an angularJs app and need to have application_beginrequest where I need to get current url in the browser.
E.g. localhost:60607/#/login : need to get /login
localhost:60607/#/activity : need to get /activity
Also whenever user hits a refresh or when page loads again and goes into beginrequest it should have the same response.
I tried with context.Request.Path but it gives "/" only.
bookmarks are not sent by browser to server, bookmarks are used for navigating inside the page. You have to get book mark using javascript and send it using different parameter to get that bookmark value at server side.
Data after "#" symbol is supposed to be client side only (usually browsers strip away those pieces, application servers usually ignore them).
If your intent is to provide users the ability to refresh the page using Angular you can:
Provide isomorphic behavior (load the page server side) but if you are using Angular JS ver 1.x is not as simple as you imagine
Provide double routing behavior (*):
avoid using the "#" symbol for url and provide user simple url like /login or /activity
manage your route client side using angular as you are supposed to do already
manage your route server side and provide the right view when requested
you can try to centralize the view management providing them using a controller instead of static content
Using the second approach is probably simpler, but you will find that:
keeping the view state is possible only for simple views (the things get complex quite quickly we introducing multiple UI element state)
to manage the double routing you have to find a compromise between client/server

How can I run a check on page-load (server-side) on a website which includes both aspx pages and mvc?

I want to run a version consistency check between the website and database on every page in the software I work on to see whether one or the other is out of sync. (background: someone could upgrade while a user is using the software, so restricting the check to the sign in page isn't realistic - also why the check is required on any page in the software).
I am not in control of the deployment, as the customer hosts the software themselves on their own hardware.
The front-end is a mixture of asp.net pages and MVC4 (gradually replacing the aspx pages with MVC) , so I can't simply just run the check on Page_Load() in our inner and outer basepages and then have something different for our MVC pages - I would rather not duplicate code for each page type.
Having a look around, I have seen filters which exist for MVC which could be an option for those pages.
I've been investigating HttpHandlers and in theory could restrict the requests down to page load and not static content.
Is there an alternative/better way to do this server side check which would have the code in just one place and would affect both aspx pages and MVC?
Depending on what it should do when its passes the check or fails the check you could set up a new controller Version with an action Check
public class Version : Controller
{
public JsonResult Check() {
return new Json((GetWebsiteVersionNumber() == GetDatabaseVersionNumber()));
}
}
You can then call this endpoint from MVC using #Html.Action in _Layout or in another view and respond accordingly. On the Web Forms side you can then call this end point using the serverside WebRequest class and take appropriate action depending upon the response from your MasterPage PageLoad event or anywhere else you prefer.
Further you could call the endpoint from a common javascript file i(ncluded on both the WebForms and MVC client side includes) and using an AJAX request get the response and deal with it there also.
Excuse syntax errors as I was writing this off the top of my head.

How to POST Data to another web application (cross domain)

Please consider the following scenario,
There are two web applications App1 & App2. A user would submit his information on App1 though a form. On click of a specific button/link on App1, the same data should be posted to a page on App2 and the user should also be redirected to the same page on App2.
I would like some help in finding out the best way to implement this functionality.
One of the approaches that I have already tried out is by creating a temporary HTML form at runtime, setting the action attribute of the form to the App2 Page and get the form posted by using javascript submit. The data can then be fetched on App2 page by using the response.form object.
This approach works well, but i was still wondering if there is any other way to implement the required functionality.
I would really appriciate if you can give some insights on using RESTful webservices to implement this, or else, using some HttpModule to intercept requests at App1 and modify redirect response to app2 or any other approach that you might find fit for the purpose.
Edit:
Using querystring isnt an option for me.
I've had a need to do similar things with feed agregation and building rss feeds from web page content on different domains.
User Gets app1 page, fills in details and submits then on the server for app1 I have a method that looks like this ...
HTMLDocument FetchURL( string url )
{
WebClient wc = new WebClient();
string remoteContent = wc.DownloadString(url);
// mshtml api is very weird but lets just say you have to do things this way ...
HtmlDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(new object[] { remoteContent });
return (HTMLDocument)doc2;
}
This function does 2 things of use ...
It gets the page of content at "url"
It parses that content in to a HTMLDocument object
Once you have this function you can then call it passing it the url to the remote page and get back a html doucment.
The functions in the HTMLDocument object will allow you to do javascript like dom queries such as :
docObject.GetElementById("id");
I then have different functions that do different things with this object based on the page / site i'm returning data from.
There is however one fatal flaw here ...
This is likely to work really well with sites that don't change much in structure and are built by code but not so well on less dynamic sites.
With stackoverflow for example its easy to pull out a question and the accepted answer for that question so I could use this code to pull and publish content from here on my own web site.
However ...
This is not going to help you for user / login related details as this sort of information is not shared to generally everyone.
It's bit like me going and trying this to link facebook profiles to my own website, I would have to go through some form of api that asked the user to authenticate their details before making the request.
simply pulling a web page based on a url only will give the other site no authentication information unless that site accepts the user login details in the quesrystring and you already have them.
You may however be able to chain requests by ripping apart my sample method, requesting the login page parsing the results, filling in the form, then posting back using the same web client instance to login then requesting the url.
The idea being that you would have a form that asks the user to put in their login details for the remote site on your site then you go and find their profile page based on that.
This would be best farmed out to a class rather than just a simple method like i have here.
In my case though i was only after something simple (the bbc top 40 uk charts) which i pulled information from not only the bbc but places like amazon, google, and youtube, then i built a page :)
It's neat but serves no functional purpose other than pulling all your other fave sources of info on to 1 page.
If you are already committed to using javascript, then why not an ajax post, and change the window.location based on the response?
You can use HttpServerUtility.Transfer this will preserve your form contents and transfer the user to the new page.
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer.aspx
I have built something like what you are describing, and I found that using a <form> tag to POST to app2 is the most reliable way... basically, the way you found that worked well.
If App2 is residing on a different domain, it's usually best to create your own interface for the submission, and have that interface handle the posting from App1 to App2.
(Browser) -> Submits form to App1 ->
(App1) -> validate input
-> stores local info
-> creates an HttpRequest/POST object
-> posts to App2
(App2) -> handles the post
<- returns the response
-> confirms the results of App2
<- returns the results to the browser.
In essense, you want to control and proxy requests from your Applications domain to any outside interfaces as much as possible.
Note: I'm answering my own question
just to have a correct answers marked
against it. All the suggestions
provided by various members here are
correct in their own way, but they
were not apt for my requirements.
Hence, I cant accept any of them as
correct.
The way I have Implemented is by creating a custom control which would have a configurable property containing the URL to post data and another one accepting a dictionary object as the data input to be posted.
This control would internally create a HTML form with action attribute set to the URL specified by the user and have the data feilds created out of the dictionary object. This form would then be posted on the button click event on the page hosting this control.

Categories