I am working on SMS send and receive functionality in an MVC3 application. How can I send a response to a URL? Any URL that hits my page should get a response like "ok" or "received".
For example, consider the code below, which is sent from a provider to my site. I need to send a response text like "ok" or received to stringResult. If I can respond to URL with some "success" parameter that would be great.
string stringResult = null;
stringpost ="parameters for url";
objWebRequest = (HttpWebRequest)WebRequest.Create("http://myip/app/action/receivesms?");
objWebRequest.Method = "POST"
if ((objProxy1 != null))
{
objWebRequest.Proxy = objProxy1;
}
objWebRequest.ContentType = "applicationwww-form-urlencoded";
objStreamWriter = new StreamWriter(objWebRequest.GetRequestStream());
objStreamWriter.Write(stringpost);
objStreamWriter.Flush();
objStreamWriter.Close();
objWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
stringResult = objStreamReader.ReadToEnd();
objStreamReader.Close();
return (stringResult);
Just do this in your controller:
public ActionResult YourAction()
{
return Content("OK");
}
Or, if you wanted to use HTTP codes instead of strings, you could do something like:
public ActionResult YourAction()
{
// 204 is the HTTP code for OK with no content
return new HttpStatusCodeResult(204);
}
stringResult = objStreamReader.ReadToEnd();
stringResult in your code recieve server response. this response contains ok or succuessfully sent.
you have to interpret the response and then send your message to the client and you can call this send smsmethod using ajax.
In ajax method call you can show dialog of "OK" or "RECIEVED"
Related
In ASP.Net Core 2.0, how can I POST data while redirecting to a third-party URL using Response.Redirect()?
Note: I have to POST this data without using the query-string.
Response.Redirect triggers a GET request which means that the only option is using a query string.
Can you trigger the redirection from the client (if any) in order to make a POST request?
You must use object if you want post data without using query string.
[HttpPost]
public IActionResult Search([FromBody] CustomerSearchRequestApiModel request)
{
if (request == null)
{
return BadRequest();
}
return Ok(request);
}
It is impossible to use Response.Redirect() to send Post request.
For a workaround, you could try HttpClient to send Post request and then return the reponse to the web browser with ContentResult as text/html.
Here is a demo code:
public async Task<ContentResult> HtmlView()
{
using (var formDataContent = new MultipartFormDataContent())
{
HttpClient client = new HttpClient();
Article article = new Article { ArticleName = "AN" };
formDataContent.Add(new StringContent("AN", Encoding.UTF8, "application/json"), "ArticleName");
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.PostAsync(#"https://localhost:44393/Articles/Create", formDataContent);
return new ContentResult
{
ContentType = "text/html",
StatusCode = (int)response.StatusCode,
Content = await response.Content.ReadAsStringAsync()
};
}
}
}
Note
Change the HttpClient part to send the right request to your own third party url with validate parameters.
I am trying to get facebook page feed ( public posts) which does not require any access token.
here's the url
https://www.facebook.com/feeds/page.php?format=json&id=1393547494231876
when i run this in browser where id= any facebook page id. it returns first 25 public posts in json format.
but when i run this in my code to get json result facebook return a page saying "unsupported browser"
this is my method . i pass it facebook page id to get posts..
public static String GetPosts(string PageId)
{
string id = PageId;
string apilink = "https://www.facebook.com/feeds/page.php?format=json&id=";
HttpWebRequest request = WebRequest.Create(apilink + id) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
String result = reader.ReadToEnd();
return result;
}
}
Here's the result that i get in return string
Result Image String
and so on remaining page returned.
Can somebody help me how to get it working??
Update
Found Answer...
I Have To Set User agent to make Facebook think i am a browser..
so just added
request.UserAgent = ".NET Framework";
and i worked.
Thanks to All.
Found Answer... I Have To Set User agent to make Facebook think i am a browser.. so just added request.UserAgent = ".NET Framework"; and i worked. Thanks to All.
I am trying to implement a RESTful web API on ASP.Net.
To test this Web API I created a small client application, which uses HttpClient.PostAsync.
I add some parameters in a HttpContent object, but whatever I try, I cannot find these posted parameters at server side in my Web API.
Code at client side:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var customer = new Customer() { FirstName = "test", LastName = "test" };
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<Customer>(customer, jsonFormatter);
HttpResponseMessage response = await client.PostAsync(base_url, content);
Code at server side:
string httpMethod = Request.HttpMethod;
if (httpMethod == "POST")
{
string firstName = Request.QueryString["FirstName"];
string lastName = Request.QueryString["LastName"];
}
If I set a breakpoint at server side I see that Request.AcceptTypes is equal to "application/json", so probably the formatting type was received at server side.
However, Request.QueryString is empty all the time and I don't know how to retrieve the posted parameters...
Can anyone help me out?
Thanks in advance!
I found this useful link which helped me out:
http://www.asp.net/web-api/tutorials/hands-on-labs/build-restful-apis-with-aspnet-web-api
That works!
I try to use the new .net 4.5 HttpClient from System.net.http.
I set-up my client like this
CookieContainer cookieJar = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler
{
CookieContainer = cookieJar,
AllowAutoRedirect = true
};
handler.UseCookies = true;
handler.UseDefaultCredentials = false;
HttpClient client = new HttpClient(handler as HttpMessageHandler);
then I do a client.GetAsync(url)
now I am inspecting the response and try to get the cookie / session values for a following post.
I try to test a login scenario of an existing page via code...
How do I get the cookie information in a response? Or do I walk on a wrong path here?
Any explanation would be fantastic...
The cookie exists in the form of a header that is the instruction to create the cookie on the client. Those headers have the form of "Set-Cookie" as the actual header, with the value of "CookieTitle={form encoded value}". Getting that cookie looks like this:
var cookieTitle = "MyCookieTitle";
var response = ... // get response object
var cookie = response.Headers.GetValues("Set-Cookie").First(x => x.StartsWith(cookieTitle));
That gets you the raw string of the header, which will look like this:
CookieTitle=this+is+the+value+of+the+cookie
You can check the 'Set-Cookie' header of the HTTP response.
You don't need to get the cookies and re-specify them for your next POST. The HttpClient will take care of doing that for you.
As long as the URL that you are POSTing to is within the path that was defined by the cookie then the cookie will automatically be resent with the request.
For example, if you create your cookie like this,
public class CookieController : ApiController
{
public HttpResponseMessage Get() {
var httpResponseMessage = new HttpResponseMessage();
var cookieHeaderValues = new List<CookieHeaderValue>();
cookieHeaderValues.Add(new CookieHeaderValue("foo","bar")
{Domain = "myhost",Path = "/"});
httpResponseMessage.Headers.AddCookies(cookieHeaderValues);
return httpResponseMessage;
}
}
Any request to any URL below http://myhost/ will automatically be sent this cookie.
I have an MVC3 application, and my controller actions are secured using the [Authorize] attribute. So far, so good, forms auth works great. Now I want to add a JSON API to my application so some actions are accessible to non-browser clients.
I'm having trouble figuring out the 'right' design.
1) Each user has secret API key.
2) User ID 5 calls http://myapp.com/foocontroller/baraction/5?param1=value1¶m2=value2&secure_hash=someValue. Here, secure_hash is simply the SHA1 hash of param1 and param2's values appended with the secret API key for the user
2) /foocontroller/baraction will be decorated with [CustomAuthorize]. This will be an implementation of AuthorizeAttribute which will check if the request is coming in as JSON. If it is, it will check the hash and see if it matches. Otherwise, if the request is HTML, then I call into existing authorization.
I am not at all sure if this will work. Is it normal to pass a secure hash in the query string or should I be passing it in as an HTTP header? Is it better to use HTTP basic auth instead of a hash made using the secret API key?
Tips from anyone who has made a web API using ASP.NET MVC would be welcome!
I pass the secret API key along with username and password in the request body. Once authorized, a token is generated and the client has to pass that in the Authorization header. This gets checked in the base controller on each request.
Client calls myapp.com/authorize which return auth token.
Client stores auth token locally.
Client calls myapp.com/anycontroller, with authtoken in Authorization header.
AuthorizeController inherits from controller.
Anycontroller inherits from a custom base controller which performs the authorization code.
My example requires the following route which directs POST requests to an ActionResult named post in any controller. I am typing this in by hand to simplify it as much as possible to give you the general idea. Don't expect to cut and paste and have it work :)
routes.MapRoute(
"post-object",
"{controller}",
new { controller = "Home", action = "post" {,
new { httpMethod = new HttpMethodConstraint("POST")}
);
Your auth controller can use this
public class AuthorizationController : Controller
{
public ActionResult Post()
{
string authBody;
var request = ControllerContext.HttpContext.Request;
var response = ControllerContext.HttpContext.Response;
using(var reader = new StreamReader(request.InputStream))
authBody = reader.ReadToEnd();
// authorize based on credentials passed in request body
var authToken = {result of your auth method}
response.Write(authToken);
}
}
Your other controllers inherit from a base controller
public class BaseController : Controller
{
protected override void Execute(RequestContext requestContext)
{
var request = requestContext.HttpContext.Request;
var response = requestContext.HttpContext.Response;
var authToken = Request.Headers["Authorization"];
// use token to authorize in your own method
var authorized = AmIAuthorized();
if(authorized = false) {
response.StatusCode = 401;
response.Write("Invalid token");
return;
}
response.StatusCode = 200; // OK
base.Execute(requestContext); // allow inheriting controller to continue
}
}
Sample code to call the api
public static void ExecutePostRequest(string contentType)
{
request = (HttpWebRequest)WebRequest.Create(Uri + Querystring);
request.Method = "POST";
request.ContentType = contentType; // application/json usually
request.Headers["Authorization"] = token;
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
writer.Write(postRequestData);
// GetResponse reaises an exception on http status code 400
// We can pull response out of the exception and continue on our way
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
finally
{
using (StreamReader reader =
new StreamReader(response.GetResponseStream()))
responseText = reader.ReadToEnd();
httpcontext = HttpContext.Current;
}
}