Newbie question … sorry ;-)
I have to write and to integrate a new website in a complex web application.
My new (MVC2) website will be hosted on a separate server and only called when the user clicks on a link in the already existing, complex website.
Means I(!) define the URL which calls my(!) new website.
But “they” (the calling, already existing, complex web application/website) will add an attribute to the url. This attribute is the sessionID.
Ok, I think I understand already that this calls my (MVC2) controller.
But how can I get in my (MVC2) controller the “calling URL” (which include the added sessionID)?
Hopefully that someone understand what I ask ;-)
Thanks in advance!
I want just share my little parser - hopefully it helps someone. ;-)
Also requests like
(Request.Url.Query =) "?sessionID=12345678901234567890123456789012&argumentWithoutValue&x=1&y&z=3"
will be well parsed.
Here my code:
Hashtable attributes = new Hashtable();
string query = Request.Url.Query;
string[] arrPairs = query.Split('&'); // ...?x=1&y=2
if (arrPairs != null)
{
foreach(string s in arrPairs)
{
if (!String.IsNullOrEmpty(s))
{
string onePair = s.Replace("?", "").Replace("&", "");
if (onePair.Contains("="))
{
string[] arr = onePair.Split('=');
if (arr != null)
{
if (arr.Count() == 2)
{
attributes.Add(arr[0], arr[1]);
}
}
}
else
{
// onePair does not contain a pair!
attributes.Add(onePair, "");
}
}
}
You really should set your URL and Route to be more MVC-Like. The URL you are calling should be:
newapp/controller/action/sessionId
Then set your route up:
routes.MapRoute(
"sessionId",
"{controller}/{action}/{sessionId}",
new { controller = "controller", action = "action", sessionId = 0 });
Then in your controller:
public ActionResult Action(int sessionId)
{
}
In your controller you still have direct access to the Request object, so you can use Request.Url, etc.
Does that answer your question, or is it something else that you need?
Related
I am using a .NET CORE API application with Middleware but I need the Post to read the individual values from the Body in Postman AND have the Middleware Validate a particular value in the Body, for example, the (To:) of an email; and, if it meets whatever criteria I would like to (POST) send the email on to the intended recipient (To:) without a database.
This is what my code looks like so far
using (StreamReader streamReader = new StreamReader(httpContext.Request.Body, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: bufferSize, leaveOpen: true))
{
await streamReader.ReadToEndAsync();
//Do something
////From test
if (evaluate.IsSenderFromConfiguration() == true)
{
message.From = From;
}
message.To = new List<MailboxAddress> { new MailboxAddress("mail#mail.com")};
message.Subject = "Message From Create Middleware";
message.HtmlBody = "This is just a test of Middleware ";
await SendEmailAsync(message);
httpContext.Request.Body.Position = 0;
}
await httpContext.Response.WriteAsync(body);
await _next.Invoke(httpContext);
}
Here is the Post from the Controller
[HttpPost]
public IActionResult Post([FromBody] Email email)
{
var message = new Email(_message.From, _message.To, _message.Subject, _message.HtmlBody);
if (message == null)
{
return NotFound();
}
return Ok(message);
}
Right now I just have what I did in the Get to send the email. How can I have it to where the properties message.To, message.From, etc. can be set by the User/Me in Postman and if the value in message.To is valid send the email?
I think there is a way to use the httpContext.Request.Body somehow, but I don't know how in .NET Core to set each individual value separately outside of the Middleware class.
To clarify: My Post Controller DOES NOT WORK FOR FORM VALIDATION The Middleware should be doing the work and then passing it to the controller once validated. That is where I need the assistance for the Middleware class.
use FluentValidation
also use in middleware like below:
services.AddMvc(setup => {
//...mvc setup...
}).AddFluentValidation();
public function actionDone($id)
{
if ($model = $this->findModel($id)) {
$model["status"] = 3;
if ($model->save()) {
return $this->redirect(['test/index']);
}
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
It works only for the first time for each link. After that its just redirects to the 'test/index' without doing anything. Seems like browser (or smth else) remember, that if we open, for example, page site.com/?r=test/done&id=2 it should redirect to 'test/index' anyway.
Why is that? How can I fix it?
I even tried put die(); in the beginning of the method - anyway it redirects to 'test/index' until I use different link with another ID.
Thanks!
I have a problem to implement a simple HTTP redirection.
I use Liferay 6.0.6, our portlets are build with JSF2.0 / PortletFaces.
I want to call a redirection when a view is loaded (and not when an action is triggered). Currently, my function is called by the PreRenderView listener.
<f:metadata>
<f:event listener="#{myControler.dispatch}" type="preRenderView" />
</f:metadata>
In this function, i can check the permissions, do other stuff, and in some cases I want to redirect the user to a new page (not another view).
I tried several methods, unsuccessfully.
Specifically, I thought that this method would work :
getFacesContext().getExternalContext().redirect(url);
getFacesContext().responseComplete()
// => Can only redirect during ACTION_PHASE
This error is logical, but is there a solution to force the redirection.
It could be realized in another function, called otherwise, I only need the Hibernate Session (set at the beginning of the Render Phase)
Have you ideas to resolve this problem?
Thanks!
ps : <redirect /> or ?faces-redirect don't work with the portlets.
You can't do this in the render phase by design. Reasons:
It's possible that portlets are rendered asynchronously, so the page might already be displayed when your portlet is being rendered
It's possible that parts of the page are already delivered to the client, so that the HTTP Headers are already sent - for this reason, by design you don't have access to them in the render phase
What would be the expected outcome if two portlets rendered on the same page would decide that they'd like to forwards to another page? Who would win?
A hacky workaround is to render some javascript redirect, but this is veeeery un-portal-like and can mess up other's expectations (plus, parts of the page might already be rendered, causing your users to fill a form only to be redirected by your javascript routine.
Please rethink the problem and come up with a different solution - it's really worth doing this in a portal environment.
I use this and it works for me:
public void preRenderView() throws IOException {
if (!checkUtente()) {
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "errore.xhtml?faces-redirect=true");
fc.renderResponse();
}
}
Use the below method it will work
public static void redirect(final String url) throws IOException {
final javax.portlet.PortletResponse portletResponse
= getPortletResponse();
if (portletResponse instanceof ActionResponse) {
final javax.portlet.ActionResponse actionResponse
= (javax.portlet.ActionResponse) portletResponse;
actionResponse.sendRedirect(url);
} else if (portletResponse instanceof ResourceResponse) {
final FacesContext ctx = FacesContext.getCurrentInstance();
if (ctx.getPartialViewContext().isPartialRequest()) {
final ResourceResponse portletResResp
= (ResourceResponse) portletResponse;
PartialResponseWriter pwriter;
final ResponseWriter writer = ctx.getResponseWriter();
if (writer instanceof PartialResponseWriter) {
pwriter = (PartialResponseWriter) writer;
} else {
pwriter = ctx.getPartialViewContext()
.getPartialResponseWriter();
}
portletResResp.setContentType(Constants.CONTENT_TYPE);
portletResResp.setCharacterEncoding(Constants.ENCODING_TYPE);
// addResponseHeader("Cache-Control", "no-cache");
pwriter.startDocument();
pwriter.redirect(url);
pwriter.endDocument();
ctx.responseComplete();
} else {
throw new UnsupportedEncodingException(
"Can only redirect during RESOURCE_PHASE "
+ "if a Partial-(JSF AJAX)-Request has "
+ "been triggered");
}
} else {
throw new UnsupportedEncodingException(
"Can not redirect during the current phase: "
+ portletResponse.getClass().getSimpleName());
}
}
Just started today some dev using Facebook SDK and i can't figure out the logic followed to link the members of the expando object to the fields in the Graph API objects in the example bellow that was taken from facebook C# SDK docs:
public ActionResult RestFacebookPage()
{
FacebookApp app = new FacebookApp();
dynamic parameters = new ExpandoObject();
parameters.page_ids = "85158793417";
parameters.method = "pages.getInfo";
parameters.fields = "name";
dynamic result = app.Api(parameters);
return View("FacebookPage", result);
}
I do understand the page_ids and fields, but not pages.getInfo. It would be great if someone could enlighten me here and tell me where in the documentation i can find a reference that leads me to this....
Thanks a lot!
Not sure I understand what you are asking but there is a pretty decent example about translating php to facebook-c#-sdk over on their project page. Then you can just look up the official facebook developer documentation directly.
If you were asking more off a "how is this implemented" type of question, the best way to do this in my opinion is to break at the line containing app.Api and from there just step through the code. In the Api method there is a check to see if the parameters dictionary contains a key "method". If there is, the sdk figures the call is bound for the old rest api, not the graph api. A few stack frames lower we find the code that makes the url:
protected virtual Uri GetUrl(string name, string path, IDictionary parameters)
{
Contract.Requires(!String.IsNullOrEmpty(name));
Contract.Ensures(Contract.Result() != default(Uri));
if (_domainMaps[name] == null)
{
throw new ArgumentException("Invalid url name.");
}
UriBuilder uri = new UriBuilder(_domainMaps[name]);
if (!String.IsNullOrEmpty(path))
{
if (path[0] == '/')
{
if (path.Length > 1)
{
path = path.Substring(1);
}
else
{
path = string.Empty;
}
}
if (!String.IsNullOrEmpty(path))
{
uri.Path = UriEncoder.EscapeDataString(path);
}
}
if (parameters != null)
{
uri.Query = parameters.ToJsonQueryString();
}
return uri.Uri;
}
You should probably step into this method yourself to see what the variables hold and it should make sense to you. The source is always the best documentation. Hope this helps.
strugglin to create event in javascript as
api.events_create(eventInfo,function(result,ex){
is failing and
catch(FacebookRestClientException){
gives
TypeError: api.events_create is not a function message=api.events_create is not a function
any clue
Some more context would help in debugging this.
You've created the api object, yes? (e.g., var api = FB.Facebook.apiClient;)
I'm having the same problem. If I look at the list of functions attached to FB.Facebook.apiClient using a DOM inspector, events_create() does not exist - even though other methods like events_get() and feed_publishUserAction() are there.
Facebook might have deliberately omitted it.
api.callMethod works - have put a sample call , hope it helps
var eventInfo = {
"name":this.name.value,
"category":"1",
"subcategory":"2",
"host":"My Host",
"location":"JP Nagar",
"city":"Bang",
"start_time":starttime,
"end_time":endtime};
function createEvent(eventinfo) {
try{
//check if user has extended permission to create otherwise prompt him for same
api.users_hasAppPermission('create_event',function(res,ex){
if (res == 0)
FB.Connect.showPermissionDialog("create_event",
function(res,ex){alert("Congratulations events");});
});
dict = {};
dict['event_info'] = eventinfo;
//provide a call back or a sequencer
var ret = api.callMethod(
'events.create',
dict,
function(eventid,ex){
console.log(data);
});
return ret;
}
catch(FacebookRestClientException){
console.log(FacebookRestClientException);
}
return;
}//createEvent routine