how to perform redirect in web Api c# and open the page like Window.open in JavaScript - asp.net-core-webapi

[EnableCors("AllowOrigin")]
[HttpPost("RedirectRequest")]
public HttpResponseMessage InitiateRedirectRequest()
{
var response = new HttpResponseMessage(HttpStatusCode.Moved);
response.Headers.Location = new Uri("https://www.google.com");
return response;
}

Related

Redirect from one WebAPI to an another WebAPI and getting the response

I want to create lets say a master/core api.Want to check for a certain parameter value and redirect to a an external api hosted in the same server.I have an api with uri http://hello.test.com/auth which takes two auth params Username and Password.Now i add a third parameter lets say Area.
{
"Username":"jason",
"Password":"bourne",
"Area":"mars"
}
Now coming to the master api, if with this uri for example http://master.test.com/v1/mster and i pass Username, Password and Area,and if the Area has value of lets say "mars" it should call the external mars api having uri http://mars.test.com/auth ,do the auth the process and return the response in the master api.is this possible?
With my /auth api i have this controller returning the response :
[HttpPost]
[Route(ApiEndpoint.AUTH)]
public HttpResponseMessage Auth(Login authBDTO)
{
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
using (AccountBusinessService accountService = new AccountBusinessService())
{
var result = accountService.Auth(authBDTO);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
}
Any Help Appreciated.Couldnt find this exact scenario in here.Sorry if too naive.
Found a workaround.This did the work.
[Route(ApiEndpoint.SAS)]
public IHttpActionResult esp(Login auth)
{
if (auth.Coop == "PMC")
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:60069/api/v1/auth");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = auth.UserName,
Password = auth.Password
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(result);
obj.BaseUrl = "http://localhost:60069/api/v1";
return Ok(obj);
}
}

POSTing data while redirecting to a third-party URL using Response.Redirect()

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.

How to invoke the API action of type [HttpPatch] from HttpClient class in asp.net core mvc

My API has an [HttpPatch] action which i need to invoke.
[HttpPatch("{id}")]
public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument<Reservation> patch)
{
Reservation res = Get(id);
if (res != null)
{
patch.ApplyTo(res);
return Ok();
}
return NotFound();
}
I am trying it from HttpClient class but it does not have .PatchAsync() method?
Also the parameter is of type JsonPatchDocument<Reservation> and so how to send it from client when invoking this action?
Please help
You have to create an HttpRequestMessage manually and send it via SendAsync:
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://foo.com/api/foo"),
Method = new HttpMethod("patch"),
Content = new StringContent(json, Encoding.UTF8, "application/json-patch+json")
};
var response = await _client.SendAsync(request);

ASP.NET Web API Posted value not automatically map to object

I'm trying to send my request with json content to web api, bit these value isn't automatically map to my object.
This is My API Action that result in null.
[HttpPost]
public IEnumerable<string> GetCustomerByName([FromBody] Request_GetCustomerByName request)
{
// Some Action
}
If I change parameter like below I can receive my data fine. So I wonder why my json string not automatically map to object.
[HttpPost]
public IEnumerable<string> GetCustomerByName([FromBody] dynamic request)
{
// Some action
}
This is where I send my request .
public ActionResult Index()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:40175/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Request_GetCustomerByName r = new Request_GetCustomerByName()
{
Customer = new Customer() { CustomerId = 1, CustomerName = "Name" },
RequestBase = new RequestBase() { Somefield="123"}
};
var json = new JavaScriptSerializer().Serialize(r);
HttpResponseMessage response = client.PostAsJsonAsync("api/values/GetCustomerByName", json).Result;
if (response.IsSuccessStatusCode)
{
var resVal = response.Content.ReadAsStringAsync().Result;
Response.Write(resVal);
}
}
return View();
}
Thanks, I've been stuck at this point for some hour...
You should probably inspect the Json string, this online json to c# object mapper might help: http://json2csharp.com/.

Calling Put method in Web API with asp.net MVC as client

I have created a Web-api with following put method
public HttpResponseMessage Put(int id, [FromBody]DataModel model)
in the put method i pass the object and it get updated in the database. Its working i have checked it with fiddler.
Now in My MVC Application i call it using the following code
[HttpPost]
public JsonResult OrderSearch(DataModel model)
{
UpdateOrder(model).Wait();
if (putresult != null && putresult != string.Empty)
{
return Json(putresult);
}
else
{
return Json("Error in getting result");
}
}
private async Task UpdateOrder(DataModel model)
{
string json = JsonConvert.SerializeObject(model);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PutAsync("api/values/"+ model.OrderNo,new StringContent(json)).Result;
if (response.IsSuccessStatusCode)
{
putresult = await response.Content.ReadAsAsync<string>();
}
}
}
But the code does not hit my Put method on the service and putresult remains blank. I try to search about PutAsync usage but could not find anything so please help.
Using .Wait in any ASP.NET runtime application is likely to result in a deadlock. I'm not sure how you are supposed to handle async methods in MVC.

Resources